👉🏼 Click here to Join I ❤️ .NET WhatsApp Channel to get 🔔 notified about new articles and other updates.
Using LINQ Distinct to Select Unique Data

Using LINQ Distinct to Select Unique Data

LINQ

26 Articles

Improve

In this article, let's learn about how to use Distinct and DistinctBy in LINQ in .NET.

Note: If you have not done so already, I recommend you read the article on Using LINQ Skip to Select Specific Data in Collections.

Table of Contents

  1. Introduction
  2. Get Unique items using Distinct
  3. Get Unique items using DistinctBy
  4. Summary

Introduction

We can get unique piece of data from beginning of a collection using LINQ. We're going to use Distinct() and DistinctBy() methods. Let's take a look at each of these methods and how they work.

Get Unique items using Distinct

Sometimes we need to get just a distinct value out of the collection. For instance, we have a bunch of colors in there, we have a few blacks, we have a few violets, we have a few reds,etc., so what we might want to do is say I just want to see the distinct colors, I don't want them all duplicated. So, let's take a look at how we can do that using LINQ and get the unique items.

Code Sample - LINQ Distinct

Demo - LINQ Distinct Clause Demo

Let's try LINQ Distinct

  • We have Colors with duplicate data
  • Click on Distinct Button
  • Click on reset to try other combination
Color
Black
Red
Black
Red
Brown
White

Get Unique items using DistinctBy

Instead of just getting colors what if we want the entire product object? We can also extract entire product object conditionally using DistinctBy while the condition evaluates to true. This returns the first product object for each color match and ignores the remaining for same color.

Code Sample - LINQ DistinctBy

Demo - LINQ DistinctBy Clause Demo

Let's try LINQ DistinctBy

  • We have Product class with following properties - Id, Name, Color, Price, Size
  • Enter the expression by which you would like to list.
  • Click on Distinct Button
  • Click on reset to try other combination
Id Name Color Price Size
1 Shirt Black 1000 18
2 Shirt Red 1500 28
3 Shirt Black 2000 38
4 Shirt Red 2500 48
5 Shirt Brown 3000 58
6 Shirt White 3500 68

Summary

In this article we learn't how to get unique data within collection using Distinct and DistinctBy. We also learnt how to get unique object by passing an expression. All these can be used with any IEnumerable or IQueryable types.

👉🏼 Click here to Join I ❤️ .NET WhatsApp Channel to get 🔔 notified about new articles and other updates.
  • LINQ
  • Distinct
  • DistinctBy
  • Unique