开发者

How can I define variables in LINQ?

开发者 https://www.devze.com 2022-12-10 19:47 出处:网络
This code: string[] files = {\"test.txt\", \"test2.txt\", \"notes.txt\", \"notes.doc\", \"data.xml\",

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?


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);
}


You could do this

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


If you don't want to use the from kind of syntax, you can do something similar with the Select method:

var extensions = files
        .Select(x => new { Name = x, Dot = x.IndexOf('.') + 1 })
        .Select(x => x.Name.Substring(x.Dot));

Although, like Greg, I would recommend using the Path.GetExtension method. And with methods, that could like like this:

var extensions = files
        .Select(x => Path.GetExtension(x));

And in this case I really think that is a lot easier to read than the suggested linq statements.


To write it to the console, you can do this:

extensions
    .ToList()
    .ForEach(Console.WriteLine);
0

精彩评论

暂无评论...
验证码 换一张
取 消