删除列表中的重复对象 [英] Remove duplicates object in a list

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

问题描述




我有一个在Toponyme类中声明的对象列表,它实现了IEQuatable,有四个属性City,CityGeoCode,County,State,Country。

我正在尝试删除重复但没有成功。



我尝试过:



var liste = Liste.GroupBy(c => c.City + c.CityGeoCode + c.County + c.Region + c.Country).Select(c => c.First()) .ToList();





IEnumerable< toponyme> liste2 = Liste.Distinct()。ToList();



两者都没有成功。



谢谢你你的帮助。

Hi
I have a list of objects declared in a class Toponyme implementing IEQuatable with four proprties City, CityGeoCode, County, State, Country.
I'm trying to remove the duplicates but without sucess.

What I have tried:

var liste = Liste.GroupBy(c => c.City + c.CityGeoCode + c.County + c.Region + c.Country).Select(c => c.First()).ToList();
and also

IEnumerable<toponyme> liste2 = Liste.Distinct().ToList();

Both without success.

Thanks for your help.

推荐答案

我这样做的方法是使用与比较器的区别:

The way I'd do it is to use Distinct with a comparer:
public class MyClass
    {
    public string Name { get; set; }
    public string Other { get; set; }
    public MyClass(string a, string b)
        {
        Name = a; Other = b;
        }
    }
public class MyClassComp : IEqualityComparer<MyClass>
    {
    public bool Equals(MyClass x, MyClass y)
        {
        return x.Name == y.Name && x.Other == y.Other;
        }

    public int GetHashCode(MyClass obj)
        {
        if (Object.ReferenceEquals(obj, null)) return 0;
        int hashName = obj.Name == null ? 0 : obj.Name.GetHashCode();
        int hashOther = obj.Other == null ? 0 : obj.Other.GetHashCode();
        return hashName ^ hashOther;
        }
    }

我可以用它来做你想做的事:

I can then use that to do what you want:

List<MyClass> list = new List<MyClass>();
list.Add(new MyClass("A", "A"));
list.Add(new MyClass("A", "A"));
list.Add(new MyClass("A", "B"));
list.Add(new MyClass("A", "C"));
list.Add(new MyClass("B", "A"));
list.Add(new MyClass("B", "A"));
list.Add(new MyClass("B", "B"));
list.Add(new MyClass("B", "B"));
List<MyClass> newList = list.Distinct(new MyClassComp()).ToList();


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

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