Reputation: 610
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
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