find duplicates in a list in csharp

Here's how you can find duplicates in a list in CSharp using LINQ:

main.cs
List<int> myList = new List<int>() { 2, 5, 6, 7, 8, 5, 1, 3, 6, 9 };
var duplicates = myList.GroupBy(x => x).Where(g => g.Count() > 1).Select(g => g.Key);
foreach (var duplicate in duplicates)
{
    Console.WriteLine(duplicate);
}
231 chars
7 lines

Explanation:

  • First, we create a list of integers called myList with some duplicates.
  • Then, we use the GroupBy method to group the elements of the list by their values.
  • We then use the Where method to filter the groups to only those that have a count greater than 1 (i.e., the duplicates).
  • Finally, we use the Select method to select the key of each duplicate group (i.e., the duplicated value).
  • We then loop through each duplicate and print it to the console.

gistlibby LogSnag