16 Ekim 2016 Pazar

Lİnq GroupBy ile KeySelector + KeyComparer

Giriş
İmzası şöyle
public static IEnumerable<IGrouping<TKey, TSource>> GroupBy<TSource, TKey>(
    this IEnumerable<TSource> source,
    Func<TSource, TKey> keySelector,
    IEqualityComparer<TKey> comparer
)
Elimizde bir A Listesi olsun. A'nın içinde de B Listesi olsun.
var exampleList = new List<A>
{
  // Should be in first group
  new A { ListProp = new List<B>
  {
    new B { Prop = new C { Number = 0 }},
    new B { Prop = new C { Number = 1 }}
  }},
  // Should be in first group
  new A { ListProp = new List<B>
  {
    new B { Prop = new C { Number = 0 }},
    new B { Prop = new C { Number = 1 }}
  }},
  ...
};
B listesine göre gruplama yapmak istersek önce bir key comparer tanımlarız.
public class ListOfBEqualityComparer : IEqualityComparer<List<B>>
{
  public bool Equals(List<B> x, List<B> y)
  {
    // you can also implement IEqualityComparer<B> and use the overload
    return x.SequenceEqual(y);
  }

  public int GetHashCode(List<B> obj)
  {
    //implementation of List<T> may not work for your situation
    return obj.GetHashCode();
  }
}
Daha sonra bu key comparer nesnesini kullanırız. Şöyle yaparız.
var groupedExampleList = exampleList.GroupBy(x => x.ListProp, 
                                             new ListOfBEqualityComparer());

Hiç yorum yok:

Yorum Gönder