dan*_*gph 17 linq group-by iequatable
我正在尝试使用显式键类型对某些对象执行Linq GroupBy.我没有传递IEqualityComparer给GroupBy,所以根据文档:
默认的相等比较器
Default用于比较键.
它解释了EqualityComparer<T>.Default这样的属性:
该
Default属性检查type是否T实现System.IEquatable<T>泛型接口,如果是EqualityComparer<T>,则返回 使用该实现的类型.
在下面的代码中,我正在对一组Fred对象进行分组.它们有一个名为的密钥类型FredKey,它实现了IEquatable<FredKey>.
这应该足以使分组工作,但分组不起作用.在下面的最后一行我应该有2组,但我没有,我只有3组包含3个输入项.
为什么分组不起作用?
class Fred
{
public string A;
public string B;
public FredKey Key
{
get { return new FredKey() { A = this.A }; }
}
}
class FredKey : IEquatable<FredKey>
{
public string A;
public bool Equals(FredKey other)
{
return A == other.A;
}
}
class Program
{
static void Main(string[] args)
{
var f = new Fred[]
{
new Fred {A = "hello", B = "frog"},
new Fred {A = "jim", B = "jog"},
new Fred {A = "hello", B = "bog"},
};
var groups = f.GroupBy(x => x.Key);
Debug.Assert(groups.Count() == 2); // <--- fails
}
}
Run Code Online (Sandbox Code Playgroud)
Nei*_*eil 18
来自MSDN
如果实现IEquatable,还应该覆盖Object :: Equals(Object)和GetHashCode()的基类实现,以使它们的行为与IEquatable :: Equals方法的行为一致.如果您重写Object :: Equals(Object),则在对类的静态Equals(System.Object,System.Object)方法的调用中也会调用重写的实现.这确保了Equals()方法的所有调用都返回一致的结果.
将此添加到FredKey,它应该工作
public override int GetHashCode()
{
return A.GetHashCode();
}
Run Code Online (Sandbox Code Playgroud)
这是一个完整的小提琴示例.注意:该示例与问题的示例略有不同.
以下实现IEquatable可以作为TKeyin GroupBy.请注意,它包括GetHashCode和Equals.
public class CustomKey : IEquatable<CustomKey>
{
public string A { get; set; }
public string B { get; set; }
public bool Equals(CustomKey other)
{
return other.A == A && other.B == B;
}
public override int GetHashCode()
{
return string.Format("{0}{1}", A, B).GetHashCode();
}
}
public class Custom
{
public string A { get; set; }
public string B { get; set; }
public string C { get; set; }
}
public static void Main()
{
var c = new Custom[]
{
new Custom {A = "hello", B = "frog" },
new Custom {A = "jim", B = "jog" },
new Custom {A = "hello", B = "frog" },
};
var groups = c.GroupBy(x => new CustomKey { A = x.A, B = x.B } );
Console.WriteLine(groups.Count() == 2);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9710 次 |
| 最近记录: |