开发者

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 commu开发者_运维知识库nity had a solution. Thanks!


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


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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜