【发布时间】:2014-12-09 17:00:23
【问题描述】:
我知道HashSet<T>.SetEquals 方法,但是应该何时以及如何使用CreateSetComparer?
documentation 声明:“仅在一个级别检查相等性;但是,您可以将其他级别的比较器链接在一起以执行更深入的相等性测试”
一个简单的例子是什么?
特别是,如果我比较的集合中的每个项目也包含一个 HashSet ,那么CreateSetComparer 的正确用法是什么?
这是我的出发点。我想知道CreateSetComparer方法是否适用以及如何正确使用:
public class Foo : IEquatable<Foo>
{
public string Label { get; set; }
public string Value { get; set; }
public override string ToString() {return String.Format("{0}:{1}", Label, Value); }
// assume for this example that Label and Value are immutable once set;
public override int GetHashCode(){ return ToString().GetHashCode(); }
// simplified equality check; assume it meets my needs for this example;
public bool Equals(Foo other){ return String.Equals(this.ToString(), other.ToString()); }
}
public class FooGroup : IEquatable<FooGroup>
{
public int GroupIndex {get; set;}
public HashSet<Foo> FooCollection {get; set;}
// -----------------------------
// Does HashSet.CreateSetComparer somehow eliminate or simplify the following code?
// -----------------------------
public override int GetHashCode()
{
int hash = GroupIndex;
foreach(Foo f in FooCollection)
hash = hash ^ (f.GetHashCode() & 0x7FFFFFFF);
return hash;
}
public bool Equals(FooGroup other)
{
// ignore missing null checks for this example
return this.GroupIndex == other.GroupIndex && this.FooCollection.SetEquals(other.FooCollection);
}
}
public class GroupCollection : IEquatable<GroupCollection>
{
public string CollectionLabel {get; set;}
public HashSet<FooGroup> AllGroups {get; set;}
// -----------------------------
// Does HashSet.CreateSetComparer somehow eliminate or simplify the following code?
// -----------------------------
public override int GetHashCode()
{
int hash = CollectionLabel.GetHashCode();
foreach(FooGroup g in AllGroups)
hash = hash ^ (g.GetHashCode() & 0x7FFFFFFF);
return hash;
}
public bool Equals(GroupCollection other)
{
// ignore missing null checks for this example
return String.Equals(this.CollectionLabel, other.CollectionLabel) && this.AllGroups.SetEquals(other.AllGroups);
}
}
忽略关于系统设计等的争论,一个简化的用例将是:假设我提取了一组看起来像这样的复杂数据:
var newSetA = new GroupCollection{ ... }
var oldSetA = new GroupCollection{ ... }
我只是想检查一下:
if (newSetA.Equals(oldSetA))
Process(newSetA);
【问题讨论】:
-
我正在努力想出一个有用的通用案例。