复杂对象上的 GroupBy(例如 List<T>) [英] GroupBy on complex object (e.g. List<T>)
问题描述
使用 GroupBy()
和 Count() >1
我正在尝试在列表中查找我的类的重复实例.
Using GroupBy()
and Count() > 1
I'm trying to find duplicate instances of my class in a list.
类看起来像这样:
public class SampleObject
{
public string Id;
public IEnumerable<string> Events;
}
这就是我实例化和分组列表的方式:
And this is how I instantiate and group the list:
public class Program
{
private static void Main(string[] args)
{
var items = new List<SampleObject>()
{
new SampleObject() { Id = "Id", Events = new List<string>() { "ExampleEvent" } },
new SampleObject() { Id = "Id", Events = new List<string>() { "ExampleEvent" } }
};
var duplicates = items.GroupBy(x => new { Token = x.Id, x.Events })
.Where(g => g.Count() > 1)
.Select(g => g.Key)
.ToList();
}
}
duplicates
不包含任何项目.我怎样才能使分组工作?
The duplicates
contains no items. How can I make the grouping work?
推荐答案
要使对象与许多 LINQ 运算符(例如 GroupBy
或 Distinct
)一起使用,您必须要么实现 GetHashCode
&Equals
,或者您必须提供自定义比较器.
To get objects to work with many of LINQ's operators, such as GroupBy
or Distinct
, you must either implement GetHashCode
& Equals
, or you must provide a custom comparer.
在您的情况下,将属性作为列表,您可能需要一个比较器,除非您将列表设为只读.
In your case, with a property as a list you probably need a comparer, unless you made the list read only.
试试这个比较器:
public class SampleObjectComparer : IEqualityComparer<SampleObject>
{
public bool Equals(SampleObject x, SampleObject y)
{
return x.Id == y.Id && x.Events.SequenceEqual(y.Events);
}
public int GetHashCode(SampleObject x)
{
return x.Id.GetHashCode() ^ x.Events.Aggregate(0, (a, y) => a ^ y.GetHashCode());
}
}
现在此代码有效:
var items = new List<SampleObject>()
{
new SampleObject() { Id = "Id", Events = new List<string>() { "ExampleEvent"} },
new SampleObject() { Id = "Id", Events = new List<string>() { "ExampleEvent" } }
};
var comparer = new SampleObjectComparer();
var duplicates = items.GroupBy(x => x, comparer)
.Where(g => g.Count() > 1)
.Select(g => g.Key)
.ToList();
这篇关于复杂对象上的 GroupBy(例如 List<T>)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!