tôi không thể có được giải pháp NaveenBhat của để làm việc, nhận được một lỗi biên dịch:
The type arguments for method 'System.Linq.Enumerable.GroupBy(System.Collections.Generic.IEnumerable, System.Func, System.Collections.Generic.IEqualityComparer)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
Để làm cho nó làm việc, tôi thấy nó dễ nhất và rõ ràng nhất để xác định một lớp mới để lưu trữ các cột chính của tôi (GroupKey) , sau đó là một lớp riêng biệt triển khai IEqualityComparer (KeyComparer). sau đó tôi có thể gọi
var result= source.GroupBy(r => new GroupKey(r), new KeyComparer());
lớp Các KeyComparer không so sánh chuỗi với Comparer InvariantCultureIgnoreCase, vì vậy thanh danh cho NaveenBhat đã chỉ cho tôi đi đúng hướng.
phiên bản đơn giản hóa của các tầng lớp của tôi:
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
}
}
Nguồn
2014-09-05 22:19:23
này không hoạt động? 'a => {Column1 = a.Column1.ToLower(), Column2 = a.Column2.ToLower()}' –