1 回答

TA貢獻1799條經(jīng)驗 獲得超8個贊
您需要稍微修飾一下 GroupKeys 對象。由于它是一個引用類型,并且 GroupBy 使用的是Default Equality Comparer,它的部分檢查將測試引用相等性,這將始終返回 false。
您可以通過覆蓋Equals和GetHashCode方法來調(diào)整您的 GroupKeys 類以測試結(jié)構(gòu)是否相等。例如,這是由 ReSharper 生成的:
private class GroupKeys
{
public string Key1 { get; set; }
public string Key2 { get; set; }
public override int GetHashCode()
{
unchecked
{
return ((Key1 != null ? Key1.GetHashCode() : 0) * 397) ^ (Key2 != null ? Key2.GetHashCode() : 0);
}
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
return false;
if (ReferenceEquals(this, obj))
return true;
if (obj.GetType() != this.GetType())
return false;
return Equals((GroupKeys)obj);
}
public bool Equals(GroupKeys other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return string.Equals(Key1, other.Key1)
&& string.Equals(Key2, other.Key2);
}
}
- 1 回答
- 0 關(guān)注
- 261 瀏覽
添加回答
舉報