Have you ever encountered a situation where you have a list of objects and you want to remove the objects that have duplicate values for a specific property? In this article, I will show you how to achieve this in C# without using any third-party libraries.
What is the Problem?
Let’s say you have a list of Person
objects, and each Person
has a unique Id
property. However, there might be some objects in the list that have the same Id
value. Your goal is to remove these duplicate objects and keep only one instance of each Id
value in the list.
How to Solve the Problem?
To solve this problem, we can make use of the LINQ (Language Integrated Query) extension methods provided by C#. Here’s the step-by-step process to remove objects with a duplicate property from a list:
- Group the objects in the list by the property you want to check for duplicates. In our case, it’s the
Id
property of thePerson
objects. - Select the first object from each group, as it will be the one with the unique value for the property.
- Convert the result into a new list.
Here’s the code that accomplishes this:
var uniquePersons = persons.GroupBy(p => p.Id)
.Select(g => g.First())
.ToList();
Let’s break down the code and understand each step:
persons
is the original list ofPerson
objects.GroupBy(p => p.Id)
groups the objects in the list based on theirId
property.Select(g => g.First())
selects the first object from each group, effectively removing the duplicates.ToList()
converts the result into a new list.
Example
Let’s consider an example to see how this code works. Suppose we have the following list of Person
objects:
List<Person> persons = new List<Person>
{
new Person { Id = 1, Name = "John" },
new Person { Id = 2, Name = "Jane" },
new Person { Id = 1, Name = "Alice" },
new Person { Id = 3, Name = "Bob" },
new Person { Id = 2, Name = "Eve" }
};
After applying the code mentioned earlier, the uniquePersons
list will contain the following objects:
[
{ Id = 1, Name = "John" },
{ Id = 2, Name = "Jane" },
{ Id = 3, Name = "Bob" }
]
As you can see, the duplicate objects with Id
values of 1 and 2 have been removed, and only one instance of each unique Id
value remains in the uniquePersons
list.
Conclusion
In this article, we learned how to remove objects with a duplicate property from a list in C#. By utilizing the power of LINQ, we were able to achieve this without relying on any third-party libraries. The code provided is simple and efficient, making it a convenient solution for handling such scenarios in your C# projects.