Skip to content

Instantly share code, notes, and snippets.

@lurumad
Created September 12, 2014 07:29
Show Gist options
  • Select an option

  • Save lurumad/6676d6eba8f91463da03 to your computer and use it in GitHub Desktop.

Select an option

Save lurumad/6676d6eba8f91463da03 to your computer and use it in GitHub Desktop.
Reto LINQ - Distinct
//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; }
}
@javiercampos
Copy link

Distinct completo:

var distinctCustomers = duplicatedCustomers.GroupBy(x => new { x.Id, x.Name }).Select(y => y.First());

Sólo por id:

var distinctCustomers = duplicatedCustomers.GroupBy(x => x.Id).Select(y => y.First());

@lantoli
Copy link

lantoli commented Sep 12, 2014

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