[英]Using Linq to group objects that contain a list field
I have a class, let's name it as MyClass, with a public field of type IList<AnotherType>
: 我有一个类,我们将其命名为MyClass,其公共字段的类型为
IList<AnotherType>
:
class MyClass
{
public IList<AnotherType> MyListProperty {get;}
}
I also have a list of MyClass objects in my app: 我的应用程序中还有MyClass对象的列表:
list = new List<MyClass>();
I want to get a group from this "list", specifically IOrderedEnumerable<IGrouping<MyClass,AnotherType>>
using Linq, which will be used as a source to a CollectionViewSource and will be shown to the user as a grouped ListView. 我想从此“列表”中获得一个组,特别是使用Linq的
IOrderedEnumerable<IGrouping<MyClass,AnotherType>>
,该组将用作CollectionViewSource的源,并作为分组的ListView显示给用户。 How can I do this? 我怎样才能做到这一点?
In other words, I want to merge the "list" into a grouped enumerable with the keys being MyClass
instances and values being MyClass.MyListProperty
. 换句话说,我想将“列表”合并为一组可枚举的组,其键为
MyClass
实例,值为MyClass.MyListProperty
。
If I undestand you correctly, you're looking for something like this: 如果我正确地理解了您,那么您正在寻找以下内容:
list.SelectMany(x => x.MyListProperty.GroupBy(y => x));
This returns IEnumerable<IGrouping<MyClass, AnotherType>>
. 这将返回
IEnumerable<IGrouping<MyClass, AnotherType>>
。 To make it an IOrderedEnumerable
, you need to add .OrderBy(x => x.SomeOrderingProperty);
要使其成为
IOrderedEnumerable
,您需要添加.OrderBy(x => x.SomeOrderingProperty);
at the end. 在末尾。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.