Ich konnte nicht NaveenBhat-Lösung zu arbeiten, einen Compiler-Fehler bekommen:
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.
, damit es funktioniert, fand ich es am einfachsten und klarsten eine neue Klasse zu definieren meine Schlüsselspalten zu speichern (groupkey) , dann eine separate Klasse, die IEqualityComparer (KeyComparer) implementiert. Ich kann dann
var result= source.GroupBy(r => new GroupKey(r), new KeyComparer());
Die KeyComparer Klasse nennt die Saiten mit dem InvariantCultureIgnoreCase comparer nicht zu vergleichen, so einem dicken Lob für den Hinweis mich in der richtigen Richtung NaveenBhat.
Vereinfachte Versionen meiner Klassen:
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
}
}
Dies funktioniert nicht? 'a => {Column1 = a.Column1.ToLower(), Column2 = a.Column2.ToLower()}' –