使用Linq对包含列表字段的对象进行分组

本文关键字:对象 字段 Linq 包含 列表 使用 | 更新日期: 2023-09-27 18:04:33

我有一个类,让我们把它命名为MyClass,具有类型为IList<AnotherType>的公共字段:

class MyClass
{
    public IList<AnotherType> MyListProperty {get;}
}

我也有一个列表的MyClass对象在我的应用程序:

list = new List<MyClass>();

我想从这个"列表"中获得一个组,特别是IOrderedEnumerable<IGrouping<MyClass,AnotherType>>使用Linq,它将用作CollectionViewSource的源,并将作为分组ListView显示给用户。我该怎么做呢?

换句话说,我想将"列表"合并为一个分组枚举,键为MyClass实例,值为MyClass.MyListProperty

使用Linq对包含列表字段的对象进行分组

如果我没理解错的话,你是在找这样的东西:

list.SelectMany(x => x.MyListProperty.GroupBy(y => x));

返回IEnumerable<IGrouping<MyClass, AnotherType>>。要使其成为IOrderedEnumerable,您需要在末尾添加.OrderBy(x => x.SomeOrderingProperty);