hashlock
hashlock

Reputation: 610

Select distinct without creating IEqualityComparer

I want to select a distinct set of elements from a collection using Linq without creating an IEqualityComparer class. I can't figure out how to create a lambda expression that is evaluated as an IEqualityComparer to use with Distinct(). So I used grouping to, for example, select customers with distinct names:

var distinctCustomers = new List<Customer>();
var groups= customers.GroupBy (cust => cust.Name);
foreach (var g in groups)
{
  foreach (var customer in g)
  {
    distinctCustomers.Add (customer);
    break;
  }
}

But this seems icky.

I'd either like to use Distinct with a lambda expression

var distinctCustomers = customers.Distinct ( <lambda here ?> )

or a cleaner Linq expression than listed above.

Any ideas?

Upvotes: 2

Views: 2121

Answers (2)

Reed Copsey
Reed Copsey

Reputation: 564433

If you don't want to reimplement a DistinctBy (or use one like the one in MoreLINQ), you can do this via GroupBy and a Select in which you just select the first element within each group:

var distinctCustomers = customers.GroupBy(cust => cust.Name).Select(g => g.First());

Upvotes: 5

Dima
Dima

Reputation: 6741

Use MoreLINQ from Jon Skeet, which has a DistinctBy method. Or take it's implementation to your code.

IEnumerable<Customer> distinctCustomers = customers.DistinctBy(c => c.Name);

Upvotes: 1

Related Questions