Languages
[Edit]
EN

C# / .NET - count distinct elements in List

0 points
Created by:
Pearl-Hurley
559

In this article, we would like to show you how to count distinct elements in List in C#.

Quick solution:

List<string> list = new List<string> { "A", "A", "B" };

int result = list.Distinct().Count();

Console.WriteLine(result); // Output: 2

or:

List<string> myList = new List<string> { "A", "A", "B", "B" };

HashSet<string> myHashset = new HashSet<string>(myList);

int result = myHashset.Count(); // 2

 

Practical example

In this example, we count distinct elements from the list using Distinct() and Count() methods from System.Linq.

using System;
using System.Linq;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        List<string> list = new List<string> { "A", "A", "B" };

        int result = list.Distinct().Count();

        Console.WriteLine(result);
    }
}

Output:

2

2. Using HashSet

In this example, we create a HashSet from the List to remove duplicates. The number of distinct elements in the HashSet size.

using System;
using System.Linq;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        // Example List
        List<string> myList = new List<string> { "A", "A", "B", "B" };

        // Remove duplicates
        HashSet<string> myHashset = new HashSet<string>(myList);

        // Get HashSet size
        int result = myHashset.Count();

        Console.WriteLine(result); // 2
    }
}

Output:

2

References

  1. Enumerable.Distinct Method (System.Linq) | Microsoft Docs
  2. Enumerable.Count Method (System.Linq) | Microsoft Docs
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join