C# 如何在 LINQ 中定义变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1679869/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 19:57:26  来源:igfitidea点击:

How can I define variables in LINQ?

c#linq

提问by Edward Tanguay

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 variableso that in more complex LINQ queries I have this defined in one place?

有没有办法创建f.IndexOf('.')一个变量,以便在更复杂的 LINQ 查询中我在一个地方定义它?

采纳答案by Greg Beech

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

如果您使用的是 Linq,那么您可以使用let关键字来定义内联变量(问题中发布的代码实际上并未使用 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.GetExtensioninstead of parsing the string yourself (for example, your code will break if any of the files have a .in the file name).

但是,对于您发布的特定场景,我建议您使用Path.GetExtension而不是自己解析字符串(例如,如果任何文件.的文件名中有 a,您的代码就会中断)。

var ext = from file in files select Path.GetExtension(file).TrimStart('.');
foreach (var e in ext)
{
    Console.WriteLine(e);
}

回答by Brian Rasmussen

You could do this

你可以这样做

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

回答by Svish

If you don't want to use the fromkind of syntax, you can do something similar with the Selectmethod:

如果你不想使用from那种语法,你可以用这个Select方法做类似的事情:

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.GetExtensionmethod. And with methods, that could like like this:

尽管像 Greg 一样,我建议使用该Path.GetExtension方法。使用方法,可能是这样的:

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.

在这种情况下,我真的认为这比建议的 linq 语句更容易阅读。



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

要将其写入控制台,您可以执行以下操作:

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