Pregunta

Quizás estoy siendo un poco perezoso al preguntar esto aquí, pero acabo de comenzar con LINQ y tengo una función que estoy seguro de que se puede convertir en dos consultas LINQ (o una consulta anidada) en lugar de un LINQ y un par de declaraciones foreach. ¿Algún gurú de LINQ se preocupa por refactorizar este para mí como ejemplo?

La función en sí recorre una lista de archivos .csproj y extrae las rutas de todos los archivos .cs incluidos en el proyecto:

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;
        }
    }
}
¿Fue útil?

Solución

Cómo sobre: ??

        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);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top