Question

Je suis peut-être un peu paresseux à demander cela ici, mais je viens de commencer avec LINQ et j'ai une fonction qui, j'en suis sûre, peut être transformée en deux requêtes LINQ (ou une requête imbriquée) plutôt qu'en un LINQ. et quelques déclarations de foreach. Les gourous de LINQ se soucient-ils de refacturer celui-ci à titre d’exemple?

La fonction elle-même parcourt une liste de fichiers .csproj et extrait les chemins de tous les fichiers .cs inclus dans le projet:

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;
        }
    }
}
Était-ce utile?

La solution

Que diriez-vous de:

        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);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top