EN
C# / .NET - count distinct elements in List
0
points
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