Home > Backend Development > C++ > How Can I Use Lambda Expressions to Get Distinct Values in .NET?

How Can I Use Lambda Expressions to Get Distinct Values in .NET?

Linda Hamilton
Release: 2025-01-25 23:06:10
Original
776 people have browsed it

How Can I Use Lambda Expressions to Get Distinct Values in .NET?

Efficiently Identifying Unique Values in .NET with Lambda Expressions

Extracting unique elements from a collection is a frequent programming need. .NET's LINQ library offers the Distinct() method for this, but its limitations become apparent when dealing with custom objects requiring specific equality comparisons. While Distinct() accepts an IEqualityComparer, directly using lambda expressions for this comparison isn't natively supported.

A Concise Approach Using IEqualityComparer

One solution involves creating an IEqualityComparer inline:

<code class="language-csharp">var distinctValues = myCustomerList.Distinct(
    EqualityComparer<Customer>.Create((c1, c2) => c1.CustomerId == c2.CustomerId)
);</code>
Copy after login

This method, while functional, can feel somewhat cumbersome.

Alternative: Leveraging GroupBy and Select

A more elegant alternative bypasses the need for an explicit IEqualityComparer. This approach utilizes GroupBy and Select:

<code class="language-csharp">IEnumerable<Customer> filteredList = originalList
  .GroupBy(customer => customer.CustomerId)
  .Select(group => group.First());</code>
Copy after login

This groups elements based on the specified key (CustomerId in this case) and then selects the first item from each group, effectively filtering out duplicates. This provides a cleaner and more readable solution for achieving distinct values using lambda expressions.

The above is the detailed content of How Can I Use Lambda Expressions to Get Distinct Values in .NET?. 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