我正在尝试生成一个由两个字符串串联而成的项目列表框。我创建了一个实现 IEqualityComparer 的类,我想让这个列表与众不同。
private void PopulateFamily()
{
var source = _mfgOrdersData
.Select(o => new FamilySelector(o.ItemWrapper.ItemClass, o.ItemWrapper.Family))
.Distinct()
.OrderBy(f => f.CodeFamily)
.ToList();
FamilyFilterListBox.DataSource = source;
FamilyFilterListBox.ValueMember = "Family";
FamilyFilterListBox.DisplayMember = "CodeFamily";
}
class FamilySelector : IEqualityComparer<FamilySelector>
{
public FamilySelector(string code, string family)
{
Code = code;
Family = family;
}
public string Code { get; set; }
public string Family { get; set; }
public string CodeFamily { get { return string.Format("{0}\t{1}", Code, Family); } }
public bool Equals(FamilySelector x, FamilySelector y)
{
return x.Code == y.Code && x.Family == y.Family;
}
public int GetHashCode(FamilySelector obj)
{
return obj.Code.GetHashCode() ^ obj.Family.GetHashCode();
}
}
问题是我得到的列表不明显。同一项目出现多次。
我认为 Equals() 或 GetHashCode() 没有正确实现。
最佳答案
当前,您在 Distinct()
实例集合上运行 FamilySelector
,这会导致按引用相等进行比较。
要做到这一点,您应该将 IEqualityComparer
的实例传递给 Distinct()
调用:
var source = _mfgOrdersData
.Select(o => new FamilySelector(o.ItemWrapper.ItemClass, o.ItemWrapper.Family))
.Distinct(new FamilySelector())
.OrderBy(f => f.CodeFamily)
.ToList();
您应该向
FamilySelector
类添加无参数构造函数,以便可以编译代码。我还建议对
FamilySelector
类进行小幅重构。目前它保存数据并执行比较。通常 IEqualityComparer 的实现是一个只执行比较的无数据类:class FamilyData
{
public FamilyData(string code, string family)
{
Code = code;
Family = family;
}
public string Code { get; set; }
public string Family { get; set; }
public string CodeFamily { get { return string.Format("{0}\t{1}", Code, Family); } }
}
class FamilySelector : IEqualityComparer<FamilyData>
{
public bool Equals(FamilyData x, FamilyData y)
{
return x.Code == y.Code && x.Family == y.Family;
}
public int GetHashCode(FamilyData obj)
{
return obj.Code.GetHashCode() ^ obj.Family.GetHashCode();
}
}
var source = _mfgOrdersData
.Select(o => new FamilyData(o.ItemWrapper.ItemClass, o.ItemWrapper.Family))
.Distinct(new FamilySelector())
.OrderBy(f => f.CodeFamily)
.ToList();
关于c# - 使用 IEqualityComparer 根据 C# 中的两个属性生成不同的列表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49596128/