c# - 使用 Linq 从嵌套集合中选择对象

标签 c# linq

我有一个类似这样的类结构:

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/

相关文章:

c# - 用户定义的类的对象/类数组失败

c# - 如何检查 JsonObject 是否为空值(windows.data.json)

c# - C#中的递归迭代

c# - 最后添加 .ToList(或 ToArray)时出现 LINQ 'OR' 条件问题

c# - 使用 Nest 字段提升的查询不会从 Elasticsearch 返回任何结果

c# - 使用 C#/Linq 生成固定的字符串序列

c# - 在不消耗的情况下观察 BlockingCollection 中的变化

c# - 找不到部分路径

c# - 在 WPF 中,您可以在没有代码隐藏的情况下过滤 CollectionViewSource 吗?

c# - Linq 中的 DateTime.Compare