domingo, 6 de septiembre de 2015

[TIP] Mejorando Linq. Un Comparador genérico y un “DistinctBy” !!!

Intentando utilizar el “Distinct” de Linq, me he encontrado con la necesidad te tener que implementar una clase “IEqualityComparer<T>”. Concretamente tenía que obtener objetos distintos en una gran lista. Así que, después de buscar un poco, y gracias a nuestro compañero driis, me gustaría compartir la siguiente clase con vosotros. Creo que puede comenzar a formar parte de nuestros desarrollos.

1 public static class Compare
2 {
3 public static IEnumerable<T> DistinctBy<T, TIdentity>(this IEnumerable<T> source, Func<T, TIdentity> identitySelector)
4 {
5 return source.Distinct(Compare.By(identitySelector));
6
7 public static IEqualityComparer<TSource> By<TSource, TIdentity>(Func<TSource, TIdentity> identitySelector)
8 {
9 return new DelegateComparer<TSource, TIdentity>(identitySelector);
10 }
11
12 private class DelegateComparer<T, TIdentity> : IEqualityComparer<T>
13 {
14 private readonly Func<T, TIdentity> identitySelector;
15
16 public DelegateComparer(Func<T, TIdentity> identitySelector)
17 {
18 this.identitySelector = identitySelector;
19 }
20
21 public bool Equals(T x, T y)
22 {
23 return Equals(identitySelector(x), identitySelector(y));
24 }
25
26 public int GetHashCode(T obj)
27 {
28 return identitySelector(obj).GetHashCode();
29 }
30 }
31 }

La utilizaremos de cualquier de las dos formas siguientes:



  1. list.DistinctBy(item => item.Id);

  2. list.Distinct(Compare.By(item => item.Id));

O incluso, cada vez que necesitemos un “IEqualityComparer<T>” como parámetro.


 


Saludos
Juanlu

Etiquetas: ,


Comments:
There are lots of information about latest technology and how to get trained in them, like this have spread around the web, but this is a unique one according to me. The strategy you have updated here will make me to get trained in future technologies. By the way you are running a great blog. Thanks for sharing this.
Hadoop training in chennai

 
Great post! I am actually getting ready to across this information, It's very helpful for this blog.Also great with all of the valuable information you have Keep up the good work you are doing well.

digital marketing company in india
 
This was so useful and informative. The article helped me to learn something new.

Android Training in Chennai
 
This was so useful and informative. The article helped me to learn something new.

Android Training in Chennai
 
Publicar un comentario

Links to this post:

Crear un enlace



<< Home

This page is powered by Blogger. Isn't yours?