我已经实现了IEqualityComparer和IEquatable(都是为了确保),但是当我在集合上调用Distinct()方法时,它没有调用随之而来的方法。以下是在调用Distinct()时执行的代码。
ObservableCollection<GigViewModel> distinctGigs = new ObservableCollection<GigViewModel>(Gigs.Distinct<GigViewModel>());
return distinctGigs;
我想返回一个ObservableCollection,其中不包含在“Gigs” ObservableCollection 中的任何double对象。我在GigViewModel类中实现接口如下:
public class GigViewModel : INotifyPropertyChanged, IEqualityComparer<GigViewModel>, IEquatable<GigViewModel>
{
....
}
然后重写接口中提供的方法,如下所示:
public bool Equals(GigViewModel x, GigViewModel y)
{
if (x.Artiest.Naam == y.Artiest.Naam)
{
return true;
}
else
{
return false;
}
}
public int GetHashCode(GigViewModel obj)
{
return obj.Artiest.Naam.GetHashCode();
}
public bool Equals(GigViewModel other)
{
if (other.Artiest.Naam == this.Artiest.Naam)
{
return true;
}
else
{
return false;
}
}
非常感谢我得到的所有帮助。所以我创建了一个实现IEqualityComparer接口的独立类,并将它的实例传递到distinct方法中。但是这些方法仍然没有被触发。
EqualityComparer:
class GigViewModelComparer : IEqualityComparer<GigViewModel>
{
public bool Equals(GigViewModel x, GigViewModel y)
{
if (x.Artiest.Naam == y.Artiest.Naam)
{
return true;
}
else
{
return false;
}
}
public int GetHashCode(GigViewModel obj)
{
return obj.Artiest.Naam.GetHashCode();
}
}
Distinct()
调用:
GigViewModelComparer comp = new GigViewModelComparer();
ObservableCollection<GigViewModel> distinctGigs = new ObservableCollection<GigViewModel>(Gigs.Distinct(comp));
return distinctGigs;
编辑2:
GetHashCode()
方法确实被调用了!在实现新类之后。但集合仍然包含重复项。我有一个包含'艺术家'(或Artist)对象的'演出'列表。这个艺术家有一个名为Naam的属性,它是一个字符串(名称)。