[英]How to use LINQ to return substring of FileInfo.Name
我想将下面的“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();
IList<string> fileNameSubstringValues =
(
from
file in codeToGetFileListGoesHere
select
file.Name.
Substring(0, file.Name.Length -
(file.Name.Length - file.Name.IndexOf(".config.xml"))).ToList();
享受=)
如果您碰巧知道FileInfo
集合的类型,并且它是List<FileInfo>
,我可能会跳过Linq并写:
files.ConvertAll(
file => file.Name.Substring(0, file.Name.Length - (file.Name.Length - file.Name.IndexOf(".config.xml")))
);
或者如果它是一个数组:
Array.ConvertAll(
files,
file => file.Name.Substring(0, file.Name.Length - (file.Name.Length - file.Name.IndexOf(".config.xml")))
);
主要是因为我喜欢说“转换”而不是“选择”来表达我对程序员阅读此代码的意图。
但是,Linq现在是C#的一部分,所以我认为坚持阅读程序员理解Select
作用是完全合理的。 Linq方法可让您在将来轻松迁移到PLinq。
仅供参考,
file.Name.Substring(0, file.Name.Length - (file.Name.Length - file.Name.IndexOf(".config.xml")))
是相同的
file.Name.Substring(0, file.Name.IndexOf(".config.xml"));
此外,如果该字符串“.config.xml”出现在文件名末尾之前,那么您的代码可能会返回错误的内容; 您应该将IndexOf更改为LastIndexOf并检查索引位置是否返回+ 11(字符串的大小)==文件名的长度(假设您正在查找以.config.xml结尾的文件而不仅仅是.config文件.xml出现在名称的某处)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.