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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15244988/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 14:37:37  来源:igfitidea点击:

Select object from nested collection using Linq

c#linq

提问by w3dev

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.

我需要获取所有具有特定“SomeProp”值的“属性”,无论它们属于哪个属性组。

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.

例如,SomeProperty== 'A'可以在MyClassObj.AttributeGroup[0]and 中找到,MyClassObj.AttributeGroup[5]我需要编写一个 Linq(或类似的东西)来从这两个不同的属性组中获取两个对象。

Any suggestion?

有什么建议吗?

采纳答案by JustAnotherUserYouMayKnow

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:

其他 Linq 风格的语法:

IEnumerable<Attribute> attributes =
    from attributeGroup in myClassInstance.AttributeGroups
    from attribute in attributeGroup.Attributes
    where attribute.SomeProperty == 'A'
    select attribute;

回答by Marcelo Cantos

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

回答by Andreas Schlapsi

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

看看 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.

此行选择所有 MyClass 对象的所有 AttributeGroups 的所有 Attribute 对象,其中 SomeProp 等于“A”。Where 的 lambda 表达式中的 a 是 Attribute 类型。