Created
September 12, 2014 07:29
-
-
Save lurumad/6676d6eba8f91463da03 to your computer and use it in GitHub Desktop.
Reto LINQ - Distinct
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //Obten una lista de clientes no repetidos sin usar el operador Distinct y en solo una línea | |
| void Main() | |
| { | |
| var duplicatedCustomers = new List<Customer> | |
| { | |
| new Customer | |
| { | |
| Id = 1, | |
| Name = "Luis" | |
| }, | |
| new Customer | |
| { | |
| Id = 2, | |
| Name = "Jorge" | |
| }, | |
| new Customer | |
| { | |
| Id = 1, | |
| Name = "Luis" | |
| }, | |
| }; | |
| var distinctCustomers = ??? | |
| } | |
| class Customer | |
| { | |
| public int Id { get; set; } | |
| public string Name { get; set; } | |
| } |
Habría que especificar que entendemos por clientes repetidos, asumamos que Customer tiene implementado la igualdad:
Con LINQ la manera obvia es group by, también se podría hacer con un ISet.
// Si nos vale con un IEnumerable
var distinctCustomers = new HashSet(duplicatedCustomers);
// Si queremos una lista
var distinctCustomers = new HashSet(duplicatedCustomers).ToList();
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Distinct completo:
Sólo por id: