EN
C# / .NET - find duplicates in List using Linq
0 points
In this article, we would like to show you how to find duplicates in List with Linq in C#.
Quick solution:
xxxxxxxxxx
1
List<string> list = new List<string> { "A", "A", "B", "B", "B", "C", "D" };
2
3
List<string> duplicates = list.GroupBy(x => x)
4
.Where(y => y.Count() > 1)
5
.Select(z => z.Key)
6
.ToList();
7
8
// Result: ["A", "B"]
In this example, we use Linq methods to find duplicates in the List.
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> list = new List<string> { "A", "A", "B", "B", "B", "C", "D" };
10
11
List<string> duplicates = list.GroupBy(x => x)
12
.Where(y => y.Count() > 1)
13
.Select(z => z.Key)
14
.ToList();
15
16
foreach (string i in duplicates)
17
Console.WriteLine(i);
18
}
19
}
Output:
xxxxxxxxxx
1
A
2
B