thomas479
thomas479

Reputation: 537

C# Linq where list in list

I have an list called mainList. Every item in mainList contains another list called detailList.
I want to select items from mainList where a property in detailList evaluates true.

What I hoped would work:

var list = mainList.Where(x => x.detailList.Where(y => y.property == true));

This does not work, it can not convert detailList to bool.

So my question is how do I select items in the mainList where that item has a valid property inside his detailList.

Upvotes: 5

Views: 32924

Answers (3)

Noctis
Noctis

Reputation: 11783

Been answered, but here's a working example you can run in Linqpad:

void Main()
{
    var foo_list = new List<Foo>();
    foo_list.Add(new Foo(){InnerList = new List<Bar> {
        new Bar{ Pro=true,  Ind =1 },
        new Bar{ Pro=true,  Ind =2 },
        new Bar{ Pro=false, Ind =3 }
    }});
    foo_list.Add(new Foo(){InnerList = new List<Bar> {
        new Bar{ Pro=false, Ind =4 },
        new Bar{ Pro=false, Ind =5 },
        new Bar{ Pro=false, Ind =6 }
    }});

    var l = from x in foo_list
            where x.InnerList.Any(b => b.Pro)
            select x;
    l.Dump();
}

// Define other methods and classes here
class Foo{
    public List<Bar> InnerList {get;set;}
    public Foo() {
        InnerList = new List<Bar>();
    }
}

class Bar {
    public bool Pro { get; set; }
    public int Ind { get; set; }
}

The result will hold the first Foo, since some of its Bar's have a property Pro which is true

enter image description here

Upvotes: 1

CSharpie
CSharpie

Reputation: 9477

If all items must be true:

var list = mainList.Where(x => x.detailList.All(y => y.property));

if atleast one

var list = mainList.Where(x => x.detailList.Any(y => y.property));

Upvotes: 18

Daniel Slater
Daniel Slater

Reputation: 4143

Try this, any will return True if "any" items in a list meet the condition.

var list = mainList.Where(x => x.detailList.Any(y => y.property == true));

Upvotes: 3

Related Questions