如何将此代码合并为一个或两个LINQ查询?

5

我可能有点懒,在这里问这个问题,但我刚开始使用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;
        }
    }
}
1个回答

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

太棒了。我知道 StackOverflow 会比我自己读 LINQ 书更快地找到答案!非常感谢。 - Mark Heath
没问题;作为一个小优化,你可以“let inc = c.Attribute("Include").Value”,然后在inc.EndsWith(..)选择inc... - Marc Gravell

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接