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>
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!