我无法让 NaveenBhat 的解决方案正常工作,出现编译错误:
无法从用法中推断方法“System.Linq.Enumerable.GroupBy(System.Collections.Generic.IEnumerable, System.Func, System.Collections.Generic.IEqualityComparer)”的类型参数。尝试明确指定类型参数。
为了使它工作,我发现定义一个新类来存储我的键列 (GroupKey) 是最简单和最清晰的,然后是一个实现 IEqualityComparer (KeyComparer) 的单独类。然后我可以打电话
var result= source.GroupBy(r => new GroupKey(r), new KeyComparer());
KeyComparer 类确实将字符串与 InvariantCultureIgnoreCase 比较器进行比较,因此感谢 NaveenBhat 为我指明了正确的方向。
我的课程的简化版本:
private class GroupKey
{
public string Column1{ get; set; }
public string Column2{ get; set; }
public GroupKey(SourceObject r) {
this.Column1 = r.Column1;
this.Column2 = r.Column2;
}
}
private class KeyComparer: IEqualityComparer<GroupKey>
{
bool IEqualityComparer<GroupKey>.Equals(GroupKey x, GroupKey y)
{
if (!x.Column1.Equals(y.Column1,StringComparer.InvariantCultureIgnoreCase) return false;
if (!x.Column2.Equals(y.Column2,StringComparer.InvariantCultureIgnoreCase) return false;
return true;
//my actual code is more complex than this, more columns to compare
//and handles null strings, but you get the idea.
}
int IEqualityComparer<GroupKey>.GetHashCode(GroupKey obj)
{
return 0.GetHashCode() ; // forces calling Equals
//Note, it would be more efficient to do something like
//string hcode = Column1.ToLower() + Column2.ToLower();
//return hcode.GetHashCode();
//but my object is more complex than this simplified example
}
}