删除重复项,而在LINQ合并使用联盟列表 [英] Remove duplicates while merging lists using Union in LINQ
问题描述
我想在 LinqPad
合并使用 list.Union
两份名单,但我不能得到它。工作和想检查我的理解是正确的。
I am trying to merge two lists using list.Union
in LinqPad
but I can't get it to work and wanted to check my understanding is correct.
鉴于这种简单的类:
public class Test
{
public int Id { get; set;}
public int field1 { get; set; }
public bool Equals(Test other)
{
return this.Id.Equals(other.Id);
}
}
和两个列表填充是这样的:
And two lists populated like this:
List<Test> list = new List<Test>();
list.Add( new Test { Id = 1, field1 = 1});
list.Add( new Test { Id = 1, field1 = 2});
list.Add( new Test { Id = 2, field1 = 3});
list.Add( new Test { Id = 2, field1 = 4});
List<Test> list2 = new List<Test>();
list2.Add( new Test { Id = 1, field1 = 1});
list2.Add( new Test { Id = 1, field1 = 2});
list2.Add( new Test { Id = 2, field1 = 3});
list2.Add( new Test { Id = 2, field1 = 4});
我再尝试: VAR mergedList = list.Union(列表2).ToList ();
和输出使用一个简单的的foreach
循环中的数据,并得到如下的输出:
I then try: var mergedList = list.Union(list2).ToList();
and output the data using a simple foreach
loop and get this output:
ID: 1 -------- 1
ID: 1 -------- 2
ID: 2 -------- 3
ID: 2 -------- 4
ID: 1 -------- 1
ID: 1 -------- 2
ID: 2 -------- 3
ID: 2 -------- 4
我的印象是,联盟
应删除重复的返回:
I was under the impression that Union
should remove the duplicates to return:
ID: 1 -------- 1
ID: 1 -------- 2
ID: 2 -------- 3
ID: 2 -------- 4
我是不是做错了什么或曾经我误解了?
Am I doing something wrong or have I misunderstood?
此外,如果它没有明确覆盖等于$ C $工作C>方法在
测试
类?
Also, should it work without explicitly overriding the Equals
method in the Test
class?
感谢
推荐答案
在你的情况,你只需定义一些方法,即LINQ一无所知。这就像创建方法布尔HeyEquateMeWith(测试等)
和期望,这样做设置操作时,LINQ将调用它。
In your case you simply define some method, that LINQ knows nothing about. It's like creating method bool HeyEquateMeWith(Test other)
and expect, that LINQ will call it when doing set operations.
您需要定义类如下(替换 对象
的等于
和的GetHashCode
方法):
You need to define your class as following (override Object
's Equals
and GetHashCode
methods):
public class Test
{
public int Id { get; set;}
public int field1 { get; set; }
public override bool Equals(object other) //note parameter is of type object
{
Test t = other as Test;
return (t != null) ? Id.Equals(t.Id) : false;
}
public override int GetHashCode()
{
return Id.GetHashCode();
}
}
现在联盟
将调用您的重写等于
和的GetHashCode
方法。你也应该 的ALWAYS覆盖的GetHashCode
在覆盖等于
方法。
Now Union
will call your overridden Equals
and GetHashCode
methods. Also you should ALWAYS override GetHashCode
when you override Equals
method.
这篇关于删除重复项,而在LINQ合并使用联盟列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!