Select object from nested collection using Linq
c#, linq
Solution
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;
Problem
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?