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