Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I combine this code into one or two LINQ queries?

I'm perhaps being a bit lazy asking this here, but I'm just getting started with LINQ and I have a function that I am sure can be turned into two LINQ queries (or one nested query) rather than a LINQ and a couple of foreach statements. Any LINQ gurus care to refactor this one for me as an example?

The function itself loops through a list of .csproj files and pulls out the paths of all the .cs files included in the project:

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;
        }
    }
}
like image 310
Mark Heath Avatar asked Oct 18 '08 08:10

Mark Heath


People also ask

How do I join two queries in LINQ?

LINQ Join queries. As we know the JOIN clause is very useful when merging more than two table or object data into a single unit. It combines different source elements into one and also creates the relationship between them. Using the join, you can grab the data based on your conditions.

How you can merge the results from two separate LINQ queries into a single result set?

CORRECT ANSWER : Use the Concat method.

Can we do Joins in LINQ?

In a LINQ query expression, join operations are performed on object collections. Object collections cannot be "joined" in exactly the same way as two relational tables. In LINQ, explicit join clauses are only required when two source sequences are not tied by any relationship.

How many ways can you write LINQ queries?

LINQ provides you three different ways to write a LINQ query in C# or VB.


1 Answers

How about:

        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);
like image 89
Marc Gravell Avatar answered Sep 22 '22 13:09

Marc Gravell