11

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?

3 Answers 3

28

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;
Sign up to request clarification or add additional context in comments.

1 Comment

group is a keyword - use @group or rename this range variable
3

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.

Comments

0

Your example isn't clear; I can't tell what you mean by, "two object from these two different attributegroups". I'll guess that you want the groups that have attributes with the property in question:

from g in MyClassObj.AttributeGroups
where g.Any(attr => attr.SomeProperty == "A")
select g

1 Comment

He wants the two attribute-objects that fit the condition, no matter what group they are in. It's actually pretty clear.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.