Yatrix
Yatrix

Reputation: 13775

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

type 2

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!

Upvotes: 1

Views: 728

Answers (2)

Aducci
Aducci

Reputation: 26634

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;

Upvotes: 2

Anthony Pegram
Anthony Pegram

Reputation: 126804

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();

Upvotes: 7

Related Questions