Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select object from nested collection using Linq

Tags:

c#

linq

I have a class structure something like this:

class MyClass
{
    public IEnumerable<AttributeGroup> AttributeGroups { get; set; }
}

class AttributeGroup
{
    public IEnumerable<Attribute> Attributes { get; set; }
}

class Attribute
{
    public string SomeProp { get; set; }
}

I need to get all 'Attributes' which has a specific 'SomeProp' value no matter which Attribute Group they belong to.

For example, SomeProperty== 'A' can be found in both MyClassObj.AttributeGroup[0] and MyClassObj.AttributeGroup[5] and I need to write a Linq (or something like that) to fetch two objects from these two different attributegroups.

Any suggestion?

like image 821
w3dev Avatar asked Mar 06 '13 10:03

w3dev


2 Answers

First select all attributes from all attribute groups, then only select the ones with your property.

IEnumerable<Attribute> attributes =
    myClassInstance
        .AttributeGroups
        .SelectMany(x => x.Attributes)
        .Where(x => x.SomeProperty == 'A');

Other Linq-style syntax:

IEnumerable<Attribute> attributes =
    from attributeGroup in myClassInstance.AttributeGroups
    from attribute in attributeGroup.Attributes
    where attribute.SomeProperty == 'A'
    select attribute;
like image 120
JustAnotherUserYouMayKnow Avatar answered Sep 28 '22 07:09

JustAnotherUserYouMayKnow


Have a look at SelectMany (http://msdn.microsoft.com/en-us/library/bb534336.aspx).

For example:

myClassObjs.SelectMany(o => o.AttributeGroups.SelectMany(g => g.Attributes)).Where(a => a.SomeProp == "A")

This line selects all Attribute objects of all AttributeGroups of all MyClass objects where SomeProp equals "A". a in the lambda expression for Where is of type Attribute.

like image 40
Andreas Schlapsi Avatar answered Sep 28 '22 09:09

Andreas Schlapsi