如何将此代码组合成一个或两个LINQ查询?

Mar*_*ath 5 c# linq linq-to-xml

我可能有点懒,在这里问这个,但我刚开始使用LINQ而且我有一个函数,我确信可以变成两个LINQ查询(或一个嵌套查询)而不是一个LINQ和一对foreach陈述.作为一个例子,任何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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*ell 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);
Run Code Online (Sandbox Code Playgroud)