对复杂对象(例如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();
这篇关于对复杂对象(例如List< T>)进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!