[英]Group by a distinct list of integers
MyObject()
{
String dept;
List<int> id;
Object obj;
}
Using LINQ
, how can I return a list of the above objects organized as follows: 使用
LINQ
,我如何返回上述对象的列表,其组织如下:
Group all of the obj objects by [ department and EQUAL id list ]. 按[部门和等号列表]将所有obj对象分组。 The list being considered equal if it contains the same numbers, not necessarily the same order(a set).
如果列表包含相同的数字,而不一定是相同的顺序(一组),则认为该列表相等。
GroupBy
has an overload that accepts a custom IEqualityComparer<MyObject>
. GroupBy
具有接受自定义IEqualityComparer<MyObject>
的重载 。 Write one that regards two objects as equal when dept
is equal and id
is set-equal, and pass it as an argument. 编写一个在
dept
相等且id
为set-equal时将两个对象视为相等的对象,并将其作为参数传递。
A convenient way to implement set equality is to write 实现集合相等的一种简便方法是编写
new HashSet(x.id).SetEquals(new HashSet(y.id))
although this will end up being inefficient and probably not the best idea if there are lots of comparisons to make. 尽管最终将导致效率低下,并且如果进行大量比较可能不是最好的主意。
Building off of Jon's answer , if efficiency is an issue, you can store the HashSet
for each object in an anonymous object: 基于Jon的答案 ,如果效率存在问题,则可以将每个对象的
HashSet
存储在匿名对象中:
myObjects.Select(x => new { myObject = x, hashSet = new HashSet(x.id) })
.GroupBy(x => x.hashSet, HashSet<int>.CreateSetComparer())
.SelectMany(x => x.GroupBy(y => y.myObject.dept))
If you want to perform only one GroupBy
you could store the HashSet
in a Tuple
or custom class, but then you would have to create your own IEqualityComparer
. 如果只想执行一个
GroupBy
,则可以将HashSet
存储在Tuple
或自定义类中,但随后必须创建自己的IEqualityComparer
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.