Alex Rivera | Logout

How can I define variables in LINQ?

Asked 2009-11-05T11:14:46.537
26

This code:

string[] files = {"test.txt", 
    "test2.txt", 
    "notes.txt", 
    "notes.doc", 
    "data.xml", 
    "test.xml", 
    "test.html", 
    "notes.txt", 
    "test.as"};

files.ToList().ForEach(f => Console.WriteLine(
        f.Substring(
            f.IndexOf('.') + 1, 
            f.Length - f.IndexOf('.') - 1
            )
    ));

produces this list:

txt
txt
txt
doc
xml
xml
html
txt
as

Is there some way to make f.IndexOf('.') a variable so that in more complex LINQ queries I have this defined in one place?

Edit
Report

2 Answers

60

If you were using Linq then you could use the let keyword to define an inline variable (the code posted in the question isn't actually using Linq).

var ext = from file in files
          let idx = f.LastIndexOf('.') + 1
          select file.Substring(idx);

However for the specific scenario you've posted I'd recommend using Path.GetExtension instead of parsing the string yourself (for example, your code will break if any of the files have a . in the file name).

var ext = from file in files select Path.GetExtension(file).TrimStart('.');
foreach (var e in ext)
{
    Console.WriteLine(e);
}
answered 2009-11-05T11:19:06.650
9

You could do this

files.ToList().ForEach(f => { var i = f.IndexOf('.'); 
   Console.WriteLine(f.Substring(i + 1, f.Length - i - 1));}
);
answered 2009-11-05T11:17:21.783

Your Answer