问题描述
嗨
我有一个在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.
推荐答案
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();
这篇关于删除列表中的重复对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!