gpt4 book ai didi

c# - 使用 IEqualityComparer 根据 C# 中的两个属性生成不同的列表

转载 作者:行者123 更新时间:2023-12-02 14:33:16 24 4
gpt4 key购买 nike

我正在尝试生成一个由两个字符串串联而成的项目列表框。我创建了一个实现 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() 没有正确实现。

最佳答案

目前,您在 FamilySelector 实例集合上运行 Distinct(),结果是通过引用相等进行比较。

要正确执行此操作,您应该将 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com