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;
}
}
}
辉煌。我知道StackOverflow会通过阅读LINQ书籍,找到我比我自己找到的答案更快的答案!非常感谢。 – 2008-10-18 09:43:52