c# - 如何使用 LINQ 返回 FileInfo.Name 的子字符串

标签 c# .net linq

我想将下面的“foreach”语句转换为将文件名的子字符串返回到列表中的 LINQ 查询:

IList<string> fileNameSubstringValues = new List<string>();

//Find all assemblies with mapping files.
ICollection<FileInfo> files = codeToGetFileListGoesHere;

//Parse the file name to get the assembly name.
foreach (FileInfo file in files)
{
    string fileName = file.Name.Substring(0, file.Name.Length - (file.Name.Length - file.Name.IndexOf(".config.xml")));
    fileNameSubstringValues.Add(fileName);
}

最终结果将类似于以下内容:

IList<string> fileNameSubstringValues = files.LINQ-QUERY-HERE;

最佳答案

尝试这样的事情:

var fileList = files.Select(file =>
                            file.Name.Substring(0, file.Name.Length -
                            (file.Name.Length - file.Name.IndexOf(".config.xml"))))
                     .ToList();

关于c# - 如何使用 LINQ 返回 FileInfo.Name 的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/418187/

相关文章:

c# - C# 中的类型推断

c# - 我可以为 C# 制作自己的 JIT\Interpreter\Compiler 并在 Visual Studio 中使用它吗?

c# - Linq to sql/C# - 多处搜索键/值对

.net - 如何跟踪任何子控件何时在 WinForms 中获得或失去焦点?

c# - 如何使用 NServiceBus 避免 READPAST 锁定警告

c# - WinForms:SplitContainer 的替代品?

c# - 如何在 asp.net core 的 ActionFilter 中刷新响应?

c# - 添加具有数据类型属性的新 XElement

c# - Linq to SQL 连接和位置

c# - 比较两个不同 LINQ 语句的效率