Linq Distinct没有返回预期值

时间:2015-01-07 06:05:30

标签: c# .net linq equality

我正在尝试从自定义集合中获取不同项目的列表,但是比较似乎被忽略了,因为我不断在我的列表中出现重复项。我调试了代码,我可以清楚地看到我比较的列表中的值是相等的......

注意:Id和Id2值是字符串

Custom Comparer:

public class UpsellSimpleComparer : IEqualityComparer<UpsellProduct>
{
    public bool Equals(UpsellProduct x, UpsellProduct y)
    {
        return x.Id == y.Id && x.Id2 == y.Id2;
    }

    public int GetHashCode(UpsellProduct obj)
    {
        return obj.GetHashCode();
    }
}

致电代码:

var upsellProducts = (Settings.SelectedSeatingPageGuids.Contains(CurrentItem.ID.ToString())) ?
                              GetAOSUpsellProducts(selectedProductIds) : GetGeneralUpsellProducts(selectedProductIds);

// we use a special comparer here so that same items are not included
var comparer = new UpsellSimpleComparer();
return upsellProducts.Distinct(comparer);

2 个答案:

答案 0 :(得分:4)

最有可能UpsellProduct具有GetHashCode的默认实现,它为每个引用类型实例返回唯一值。

修复 - 在UpsellProduct或比较器中正确实现一个。

public class UpsellSimpleComparer : IEqualityComparer<UpsellProduct>
{
   public bool Equals(UpsellProduct x, UpsellProduct y)
   {
       return x.Id == y.Id && x.Id2 == y.Id2;
   }

   // sample, correct GetHashCode is a bit more complex
   public int GetHashCode(UpsellProduct obj)
   {
      return obj.Id.GetHashCode() ^ obj.Id2.GetHashCode();
   }

}

请注意更好的代码来计算合并GetHashCode支票Concise way to combine field hashcodes?Is it possible to combine hash codes for private members to generate a new hash code?

答案 1 :(得分:1)

即使您的GetHashCode()方法考虑了两个UpsellProduct个实例,您的Equals()也不会返回相同的值。

使用类似的东西来反映相同的逻辑。

public int GetHashCode(UpsellProduct obj)
{
    return obj.Id.GetHashCode() ^ obj.Id2.GetHashCode();
}