[英]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.