Search code examples
linqdrilldown

LINQ: Can I get a property from an object in a list, within a collection?


    foreach (ReportType t in reportsCollection)
    {
        List<Report> reps = (from r in t.reports where r.isChecked == true select r).ToList<Report>();
        foreach (Report r in reps)
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(r.path));
    }

This statement works just fine. I'm just looking for a single LINQ statement that could maybe do this.

Basically, I have a report object with a property called isChecked. reportsCollection contains several reportTypes that contains lists of reports of that type. So the collection looks like this:

type1

  • report
  • report 2
  • report 3

type 2

  • report 4
  • report 5
  • report 6

and so on.

I want a LINQ statement that will grab all reports where isChecked == true within those types. I suspect a loop is necessary, but I was curious to see if the community had a solution. Thanks!


Solution

  • You want to use SelectMany

    var query = reportsCollection.SelectMany(t => t.reports)
                                 .Where(r => r.isChecked == true)
                                 .ToList();
    

    In query expression syntax form, you might write it as

    var query = (from type in reportsCollection
                from report in type.reports 
                where report.isChecked == true
                select report).ToList();