使用except替换项删除重复项



我试图使用Linq获得一个except-wise列表,也就是说,如果存在,我想从另一个列表中减去元素列表。但以下内容不会删除重复项。

var simplifiedList = request.CountryExceptionRecords
.Where(e => !request.CopyInitialCountryExceptionRecords
.Any(c =>
c.PropString1 == e.PropString1
&& c.PropString2.Trim()  == e.PropString2.Trim()
&& c.PropString3 == e.PropString3));

编辑,将.Distinct()添加到决赛(在Where之后(就像一个符咒。但我不明白为什么它能工作,因为Records(Lists)使用的类既不实现GetHash也不实现Equal方法。

将.Dispinct((添加到final(在Where之后(就像一个符咒。但我不明白为什么它能工作,因为Records(Lists(使用的类既不实现GetHash也不实现Equal方法

这是因为从Distinct不使用LINQ到对象

Distinct()方法检查引用类型的引用相等性。这意味着它正在寻找完全相同的复制对象,而不是包含相同值的不同对象。

所以让我在示例中向您展示:

foo testA = new foo() { PropString1 = "A", PropString2 = "A", PropString3 = "A" };
foo testB = new foo() { PropString1 = "B", PropString2 = "B", PropString3 = "B" };
foo testC = new foo() { PropString1 = "C", PropString2 = "C", PropString3 = "C" };
List<foo> CountryExceptionRecords = new List<foo>();
CountryExceptionRecords.Add(testA);
CountryExceptionRecords.Add(testB);
CountryExceptionRecords.Add(testC);
CountryExceptionRecords.Add(testC); //adding duplicate item
List<foo> CopyInitialCountryExceptionRecords = new List<foo>();
CopyInitialCountryExceptionRecords.Add(testA); //same object adding second list
var simplifiedList = CountryExceptionRecords
.Where(e => !CopyInitialCountryExceptionRecords
.Any(c =>
c.PropString1 == e.PropString1
&& c.PropString2.Trim() == e.PropString2.Trim()
&& c.PropString3 == e.PropString3)).Distinct().ToList();

在这种情况下,simplifiedList计数将是2,因为列表具有相同引用的对象。

但另一方面,下面的例子并没有删除重复项,这是因为当对象具有相同的值时,它们不是相同的对象引用。在这种情况下,您需要使用IEqualityComparer

List<foo> CountryExceptionRecords = new List<foo>();
CountryExceptionRecords.Add(new foo() { PropString1 = "A", PropString2 = "A", PropString3 = "A" });
CountryExceptionRecords.Add(new foo() { PropString1 = "B", PropString2 = "B", PropString3 = "B" });
CountryExceptionRecords.Add(new foo() { PropString1 = "C", PropString2 = "C", PropString3 = "C" });
CountryExceptionRecords.Add(new foo() { PropString1 = "C", PropString2 = "C", PropString3 = "C" });
List<foo> CopyInitialCountryExceptionRecords = new List<foo>();
//This is another object wheares the values are same
CopyInitialCountryExceptionRecords.Add(new foo() { PropString1 = "A", PropString2 = "A", PropString3 = "A" });
var simplifiedList = CountryExceptionRecords
.Where(e => !CopyInitialCountryExceptionRecords
.Any(c =>
c.PropString1 == e.PropString1
&& c.PropString2.Trim() == e.PropString2.Trim()
&& c.PropString3 == e.PropString3)).Distinct().ToList();

最新更新