Distinct()
Methods vs. Lambda Expressions in C#: Exploring AlternativesThe Distinct()
extension method in System.Linq provides a convenient way to filter out duplicate elements from an enumerable object. While it can be used without arguments in simple cases, it requires a IEqualityComparer
instance to determine object equality. This can be troublesome, especially when using lambda expressions.
Distinct()
Is there an overload that accepts lambda expressions? Here’s how to do it:
You can define your own extension method that takes a lambda expression to compare elements:
<code class="language-csharp">public static IEnumerable<T> DistinctBy<T, TKey>(this IEnumerable<T> source, Func<T, TKey> keySelector) { return source.GroupBy(keySelector).Select(group => group.First()); }</code>
Usage:
<code class="language-csharp">var distinctValues = myCustomerList.DistinctBy(customer => customer.CustomerId);</code>
While IEqualityComparer
cannot be specified directly inline, a custom comparator class can be used as a workaround:
<code class="language-csharp">public class CustomerEqualityComparer : IEqualityComparer<Customer> { public bool Equals(Customer x, Customer y) { return x.CustomerId == y.CustomerId; } public int GetHashCode(Customer obj) { return obj.CustomerId.GetHashCode(); } }</code>
Usage:
<code class="language-csharp">var equalityComparer = new CustomerEqualityComparer(); var distinctValues = myCustomerList.Distinct(equalityComparer);</code>
C# language designer Anders Hejlsberg has solved this problem. He explains that defining an overload of Distinct()
that accepts a lambda expression is technically challenging because equal elements must have the same GetHashCode
return value if the object is to work properly in the internal hash table. . Therefore, IEqualityComparer
must be used.
The above is the detailed content of Can Lambda Expressions Be Used Directly with `Distinct()` in C#?. For more information, please follow other related articles on the PHP Chinese website!