2008-10-18 31 views
5

Tôi có lẽ hơi lười biếng hỏi điều này ở đây, nhưng tôi chỉ mới bắt đầu với LINQ và tôi có một chức năng mà tôi chắc chắn có thể được chuyển thành hai truy vấn LINQ (hoặc một truy vấn lồng nhau) thay vì LINQ và một vài tuyên bố cho phép. Bất kỳ chăm sóc LINQ gurus để refactor này cho tôi làm ví dụ?Làm cách nào để kết hợp mã này vào một hoặc hai truy vấn LINQ?

Chức năng bản thân vòng lặp thông qua một danh sách các file csproj và rút ra những con đường của tất cả các tập tin cs bao gồm trong dự án:

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; 
     } 
    } 
} 

Trả lời

8

Làm thế nào về:

 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

rực rỡ. Tôi biết StackOverflow sẽ tìm thấy tôi câu trả lời nhanh hơn tôi có thể tìm thấy nó bản thân mình bằng cách đọc một cuốn sách LINQ! cảm ơn rất nhiều. –

+0

Không sao cả; như một tối ưu hóa nhỏ, bạn có thể "cho inc = c.Attribute (" Bao gồm "). Giá trị", và sau đó, nơi inc.EndsWith (..) chọn inc ... –

Các vấn đề liên quan