2008-10-18 42 views
5

我可能在這裏有點懶惰,但是我剛開始使用LINQ,我有一個函數,我確信它可以變成兩個LINQ查詢(或一個嵌套查詢),而不是LINQ和幾個foreach語句。任何LINQ大師都會爲我重構這個作爲例子嗎?如何將此代碼組合成一個或兩個LINQ查詢?

函數本身遍歷的.csproj的文件列表,並翻出包含在項目中的所有的.cs文件的路徑:

static IEnumerable<string> FindFiles(IEnumerable<string> projectPaths) 
{    
    string xmlNamespace = "{http://schemas.microsoft.com/developer/msbuild/2003}"; 
    foreach (string projectPath in projectPaths) 
    { 
     XDocument projectXml = XDocument.Load(projectPath); 
     string projectDir = Path.GetDirectoryName(projectPath); 

     var csharpFiles = from c in projectXml.Descendants(xmlNamespace + "Compile") 
           where c.Attribute("Include").Value.EndsWith(".cs") 
           select Path.Combine(projectDir, c.Attribute("Include").Value); 
     foreach (string s in csharpFiles) 
     { 
      yield return s; 
     } 
    } 
} 

回答

8

如何:

 const string xmlNamespace = "{http://schemas.microsoft.com/developer/msbuild/2003}"; 

     return from projectPath in projectPaths 
       let xml = XDocument.Load(projectPath) 
       let dir = Path.GetDirectoryName(projectPath) 
       from c in xml.Descendants(xmlNamespace + "Compile") 
       where c.Attribute("Include").Value.EndsWith(".cs") 
       select Path.Combine(dir, c.Attribute("Include").Value); 
+0

輝煌。我知道StackOverflow會通過閱讀LINQ書籍,找到我比我自己找到的答案更快的答案!非常感謝。 – 2008-10-18 09:43:52