NET问答: 如何通过 Linq 踢掉 List 中的重复记录 ?

咨询区

Prasad

我有一个 Items 类,定义如下:


    class Items
    {
        public int Id { getset; }

        public string Name { getset; }

        public int Code { getset; }

        public decimal Price { getset; }
    }

现在 List<Items> 中包含了重复的数据,比如下面这样。


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

请问我如何通过 linq 的方式剔除重复记录呢 ?

回答区

Christian Hayter

你的这种情况需要给 Items 一个自定义比较器,参考如下代码。


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

Salah Akbari

我觉得有三种方式可以删除 List 中的重复记录。

  • 使用自定义的比较器,就像楼上那哥们说的。

  • 使用 GroupBy,把 Items 的所有属性名灌到匿名类型上,操作手法如下:


List<Item> a = new List<Item>
{
    new Item {Id = 1, Name = "Item1", Code = "IT00001", Price = 100},
    new Item {Id = 2, Name = "Item2", Code = "IT00002", Price = 200},
    new Item {Id = 3, Name = "Item3", Code = "IT00003", Price = 150},
    new Item {Id = 1, Name = "Item1", Code = "IT00001", Price = 100},
    new Item {Id = 3, Name = "Item3", Code = "IT00003", Price = 150},
    new Item {Id = 3, Name = "Item3", Code = "IT00004", Price = 250}
};

var distinctItems = a.GroupBy(c => new { c.Id , c.Name , c.Code , c.Price})
                     .Select(c => c.First()).ToList();

  • 重写 Equals 和 GetHashCode 方法。

public class Item
{
    public int Id { getset; }
    public string Name { getset; }
    public string Code { getset; }
    public int Price { getset; }

    public override bool Equals(object obj)
    {
        if (!(obj is Item))
            return false;
        Item p = (Item)obj;
        return (p.Id == Id && p.Name == Name && p.Code == Code && p.Price == Price);
    }
    public override int GetHashCode()
    {
        return String.Format("{0}|{1}|{2}|{3}", Id, Name, Code, Price).GetHashCode();
    }
}

然后就可以直接通过 Distinct() 过滤啦。


var distinctItems = a.Distinct();

点评区

我觉得 Salah Akbari 大佬总结的真到位😁😁😁,尤其是通过 GroupBy + Anonymous 的方式, 🐂👃,没啥好说的,学习了。


本文分享自微信公众号 - 一线码农聊技术(dotnetfly)。
如有侵权,请联系 [email protected] 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章