Home > Backend Development > C++ > How to Remove Duplicate Objects Based on a Property Using LINQ?

How to Remove Duplicate Objects Based on a Property Using LINQ?

Susan Sarandon
Release: 2025-01-15 21:57:45
Original
740 people have browsed it

How to Remove Duplicate Objects Based on a Property Using LINQ?

Extract unique objects based on properties using LINQ

When working with collections, you may encounter situations where you need to remove duplicates based on specific object properties. Suppose you have a collection of Car objects that are uniquely identified by their CarCode property. However, the collection may contain duplicates with the same CarCode. This article will demonstrate how to use LINQ to eliminate these duplicates and keep only unique Car instances.

To do this, we can use the technique of combining grouping and selection. The following code snippet demonstrates this approach:

<code class="language-csharp">List<Car> distinct =
  cars
  .GroupBy(car => car.CarCode)
  .Select(g => g.First())
  .ToList();</code>
Copy after login

In this code, we first use the GroupBy method to group cars by their CarCode property. This operation creates groups for each unique CarCode. We then use the Select method to extract the first car from each group using g.First(). This step ensures that only one Car object per unique CarCode is retained.

By executing this LINQ expression, you will get a new collection called distinct that contains only unique Car objects based on their CarCode property.

The above is the detailed content of How to Remove Duplicate Objects Based on a Property Using LINQ?. 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