【问题标题】:How can I combine this code into one or two LINQ queries?如何将此代码组合成一个或两个 LINQ 查询?
【发布时间】:2008-10-18 08:44:51
【问题描述】:

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

【问题讨论】:

    标签: c# linq linq-to-xml


    【解决方案1】:

    怎么样:

            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 书更快地找到答案!非常感谢。
    • 没问题;作为次要优化,您可以“让 inc = c.Attribute("Include").Value",然后 where inc.EndsWith(..) select inc...
    猜你喜欢
    • 2014-03-20
    • 1970-01-01
    • 1970-01-01
    • 2012-11-27
    • 1970-01-01
    • 2015-10-08
    • 1970-01-01
    • 2018-08-07
    • 2012-01-01
    相关资源
    最近更新 更多