我有一个类似这样的类结构:
class MyClass
{
public IEnumerable<AttributeGroup> AttributeGroups { get; set; }
}
class AttributeGroup
{
public IEnumerable<Attribute> Attributes { get; set; }
}
class Attribute
{
public string SomeProp { get; set; }
}
我需要获取所有具有特定“SomeProp”值的“属性”,无论它们属于哪个属性组。
例如,SomeProperty== 'A'
可以在 MyClassObj.AttributeGroup[0]
和 MyClassObj.AttributeGroup[5]
中找到> 我需要编写一个 Linq(或类似的东西)来从这两个不同的属性组中获取两个对象。
有什么建议吗?
最佳答案
首先从所有属性组中选择所有属性,然后只选择具有您的属性的属性。
IEnumerable<Attribute> attributes =
myClassInstance
.AttributeGroups
.SelectMany(x => x.Attributes)
.Where(x => x.SomeProperty == 'A');
其他 Linq 风格的语法:
IEnumerable<Attribute> attributes =
from attributeGroup in myClassInstance.AttributeGroups
from attribute in attributeGroup.Attributes
where attribute.SomeProperty == 'A'
select attribute;
关于c# - 使用 Linq 从嵌套集合中选择对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15244988/