删除重复列表中的使用LINQ [英] Remove duplicates in the list using linq
本文介绍了删除重复列表中的使用LINQ的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个类项目
与属性(ID,姓名,code,价格)
。
名单项目
填充了重复项目。
有关前:
1项目1 IT00001 $ 100个
2项目2 IT00002 $ 200
3项目3 IT00003 $ 150
1项目1 IT00001 $ 100个
3项目3 IT00003 $ 150
如何使用LINQ to删除重复的列表中?
解决方案
VAR distinctItems = items.Distinct();
要匹配只有一些属性,创建自定义相等比较,例如:
类DistinctItemComparer:&的IEqualityComparer LT;项目> { 公共布尔等于(X项,项目Y){
返回x.Id == y.Id&放大器;&安培;
x.Name == y.Name&放大器;&安培;
。,X code ==Ÿcode和;&安培;
x.Price == y.Price;
} 公众诠释GetHash code(项目的obj){
返回obj.Id.GetHash code()^
obj.Name.GetHash code()^
OBJ,code.GetHash code()^
obj.Price.GetHash code();
}
}
然后使用它是这样的:
VAR distinctItems = items.Distinct(新DistinctItemComparer());
I have a class Items
with properties (Id, Name, Code, Price)
.
The List of Items
is populated with duplicated items.
For ex.:
1 Item1 IT00001 $100
2 Item2 IT00002 $200
3 Item3 IT00003 $150
1 Item1 IT00001 $100
3 Item3 IT00003 $150
How to remove the duplicates in the list using linq?
解决方案
var distinctItems = items.Distinct();
To match on only some of the properties, create a custom equality comparer, e.g.:
class DistinctItemComparer : IEqualityComparer<Item> {
public bool Equals(Item x, Item y) {
return x.Id == y.Id &&
x.Name == y.Name &&
x.Code == y.Code &&
x.Price == y.Price;
}
public int GetHashCode(Item obj) {
return obj.Id.GetHashCode() ^
obj.Name.GetHashCode() ^
obj.Code.GetHashCode() ^
obj.Price.GetHashCode();
}
}
Then use it like this:
var distinctItems = items.Distinct(new DistinctItemComparer());
这篇关于删除重复列表中的使用LINQ的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文