2009-01-06 45 views
4

的子我想下面「的foreach」語句轉換爲LINQ查詢,返回的文件名的字符串到一個列表:如何使用LINQ返回FileInfo.Name

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; 
+2

這裏沒有查詢,只是從A []到B []的轉換。 – 2009-01-06 21:24:55

回答

6

嘗試是這樣的:

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

幾乎有時間。 – Will 2009-01-06 21:22:30

+1

投票結果:我更喜歡這裏的查詢語法的擴展方法語法,因爲實際上沒有查詢:您的目標是對所有元素執行轉換。沒有'where'或'orderby'或交叉'select'甚至'select new {x,y}。 – 2009-01-06 21:24:24

+0

@Jay,我更喜歡簡單投影的擴展方法語法,查詢語法我認爲我只在做連接時使用它... – CMS 2009-01-06 21:36:50

2
IList<string> fileNameSubstringValues = 
    (
    from 
     file in codeToGetFileListGoesHere 
    select 
     file.Name. 
     Substring(0, file.Name.Length - 
      (file.Name.Length - file.Name.IndexOf(".config.xml"))).ToList(); 

享受=)

2

如果你碰巧知道FileInfo S中收集的類型,這是一個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。

1

僅供參考,

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出現在名稱的某處)。