Home > Backend Development > C++ > Can Lambda Expressions Be Used Directly with `Distinct()` in C#?

Can Lambda Expressions Be Used Directly with `Distinct()` in C#?

Patricia Arquette
Release: 2025-01-25 22:56:12
Original
776 people have browsed it

Distinct() Methods vs. Lambda Expressions in C#: Exploring Alternatives

The 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:

Custom extension method

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>
Copy after login

Usage:

<code class="language-csharp">var distinctValues = myCustomerList.DistinctBy(customer => customer.CustomerId);</code>
Copy after login

Inline IEqualityComparer

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>
Copy after login

Usage:

<code class="language-csharp">var equalityComparer = new CustomerEqualityComparer();
var distinctValues = myCustomerList.Distinct(equalityComparer);</code>
Copy after login

Explanation by Anders Hejlsberg

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.

Can Lambda Expressions Be Used Directly with `Distinct()` in C#?

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template