The easiest way of getting unique items from list is LINQ’s Distinct() method. In this article you’ll see how to use it with both built-in types (like collection of integers) and custom types (like collection of complex type objects).
Get unique values from collection of integers
Let’s start with creating example list of items where some of them are duplicates.
Now we can use Distinct function to get collection of unique items from above list.
Print newly created collection to screen using foreach loop.
Result:
Get unique values from collection of custom objects
Let’s start with creating custom class. For the purpose of this example it’ll be Person class containing two properties: Forename and Surname.
Distinct method builds unique collection by comparing items. As a result of what we need to define custom comparer, which defines when we can say that two Person objects are the same. In our case such objects are equal when both forename and surname are equal.
As a next step we prepare example collection of items. As you can see below some of them are duplicated.
Now we’re ready to call Distinct method. This time it gets a parameter which is previously defined equality comparer. Unique collection is stored within uniqueItems variable and listed with foreach loop.
Result:
Need Help with Your C# Projects?
We offer expert support and development services for projects of any size. Contact us for a free consultation and see how we can help you succeed.
CONTACT US NOW