1
    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!

Yatrix
  • 13,361
  • 16
  • 48
  • 78
  • 1
    You might want to throw away that `.ToList()`, since that will make you loop through your list twice. First when doing `.ToList()`, and then again in the `foreach` loop. You should declare your collection as an `IEnumerable` instead, to keep it lazy. – ebb Sep 13 '11 at 15:58

2 Answers2

7

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();
Anthony Pegram
  • 123,721
  • 27
  • 225
  • 246
  • Nice. I figured there was, I just don't know LINQ well enough to pull that off yet. Such a slick technology. Thanks, man. – Yatrix Sep 13 '11 at 15:17
2

In query syntax it will look like this

var query = from t in reportCollection
            from r in t.reports 
            where r.isChecked == true
            select r;
Aducci
  • 26,101
  • 8
  • 63
  • 67