Skip to content

Instantly share code, notes, and snippets.

@chilversc
Created June 7, 2013 19:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chilversc/5731769 to your computer and use it in GitHub Desktop.
Save chilversc/5731769 to your computer and use it in GitHub Desktop.
Helper class to allow comparing part of a key in linq groupby/join operations using a specific comparer
/* Usage:
source.GroupBy (x => new {
x.TeamId,
x.Name.CompareUsing (StringComparer.OrdinalIgnoreCase)
})
*/
public struct KeyPart<T> : IEquatable<KeyPart<T>>
{
private readonly IEqualityComparer<T> comparer;
private readonly T value;
public KeyPart (T value, IEqualityComparare<T> comparer)
{
this.value = value;
this.comparer = comparer;
}
public override int GetHashCode ()
{
return comparer.GetHashCode (value);
}
public bool Equals (KeyPart<T> other)
{
return comparer.Equals (value, other.value);
}
public override bool Equals (object other)
{
return other is KeyPart<T> && Equals ((KeyPart<T>) other);
}
}
public static class KeyPart
{
public static KeyPart<T> CompareUsing<T> (this T value, IEqualityComparer<T> comparer)
{
return new KeyPart (value, comparer);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment