EN
C# / .NET - count number of element occurrences in List
0 points
In this article, we would like to show you how to count number of element occurrences in List in C#.
Quick solution:
xxxxxxxxxx
1
List<string> myList = new List<string> { "A", "B", "B", "C", "C", "C" };
2
3
var occurrences = myList.GroupBy(x => x).ToDictionary(y => y.Key, z => z.Count());
4
5
// Output:
6
// [A, 1]
7
// [B, 2]
8
// [C, 3]
In this example, we use methods from System.Linq
to group items into key / value pairs, where key is the item name and value is the number of occurrences.
xxxxxxxxxx
1
using System;
2
using System.Linq;
3
using System.Collections.Generic;
4
5
public class Program
6
{
7
public static void Main()
8
{
9
List<string> myList = new List<string> { "A", "B", "B", "C", "C", "C" };
10
11
var occurrences = myList.GroupBy(x => x).ToDictionary(y => y.Key, z => z.Count());
12
13
foreach (var item in occurrences)
14
Console.WriteLine(item);
15
}
16
}
Output:
xxxxxxxxxx
1
Output:
2
[A, 1]
3
[B, 2]
4
[C, 3]