使用 linq 删除列表中的重复项 [英] Remove duplicates in the list using linq

查看:37
本文介绍了使用 linq 删除列表中的重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有 属性(ID、名称、代码、价格)Items 类.

I have a class Items with properties (Id, Name, Code, Price).

Items 列表中填充了重复的项目.

The List of Items is populated with duplicated items.

例如:

1         Item1       IT00001        $100
2         Item2       IT00002        $200
3         Item3       IT00003        $150
1         Item1       IT00001        $100
3         Item3       IT00003        $150

如何使用linq删除列表中的重复项?

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();
    }
}

然后像这样使用它:

var distinctItems = items.Distinct(new DistinctItemComparer());

这篇关于使用 linq 删除列表中的重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆