[英]How can I combine this code into one or two LINQ queries?
我可能有點懶,在這里問這個,但我剛開始使用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;
}
}
}
怎么樣:
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.