Get distinct items from a list in C#

Get distinct items from a list in C#

To get distinct items from a list in C#, you can use the LINQ Distinct() method or create a HashSet<T> from the list. Both approaches will give you a collection of unique elements from the original list.

Here's how to do it:

Using LINQ Distinct() method:

using System; using System.Collections.Generic; using System.Linq; List<int> numbers = new List<int> { 1, 2, 2, 3, 4, 4, 5 }; // Get distinct items using the Distinct() method List<int> distinctNumbers = numbers.Distinct().ToList(); foreach (int number in distinctNumbers) { Console.WriteLine(number); } 

Output:

1 2 3 4 5 

Using HashSet<T>:

using System; using System.Collections.Generic; List<int> numbers = new List<int> { 1, 2, 2, 3, 4, 4, 5 }; // Create a HashSet from the list to get distinct items HashSet<int> distinctNumbersSet = new HashSet<int>(numbers); foreach (int number in distinctNumbersSet) { Console.WriteLine(number); } 

Output:

1 2 3 4 5 

Both approaches will remove duplicate elements from the list and give you a collection with only distinct items. Choose the method that suits your specific use case or preference. If you need the distinct items in a new list, use Distinct() method. If you need a data structure that automatically ensures uniqueness, use HashSet<T>.

Examples

  1. How to get distinct items from a list in C#?

    var distinctItems = myList.Distinct().ToList(); 

    Description: This code snippet demonstrates using LINQ's Distinct() method to retrieve unique items from a list. The result is converted to a list using ToList().

  2. How to filter out duplicates from a list in C#?

    var distinctItems = myList.GroupBy(x => x).Select(g => g.First()).ToList(); 

    Description: This code snippet uses LINQ's GroupBy() method followed by Select() to extract the first item from each group, effectively removing duplicates.

  3. Find unique elements in a list using HashSet in C#

    var distinctItems = new HashSet<T>(myList).ToList(); 

    Description: This code snippet utilizes HashSet<T> to automatically eliminate duplicates and convert the resulting set back to a list.


More Tags

nsenumerator signal-processing access-denied android-viewmodel linq-to-sql ignore-case dispatch-async led memcached wkwebview

More C# Questions

More Fitness Calculators

More Dog Calculators

More Electronics Circuits Calculators

More Geometry Calculators