2

Possible Duplicate:
How to Count Duplicates in List with LINQ

Any idea how do you count a duplicate in linq. Let's say i have a list of Student objects where i wanna find the amount of student called 'John'?

Community
  • 1
  • 1
danial
  • 607
  • 2
  • 12
  • 20

2 Answers2

9

You can use GroupBy:

var students = new List<string>{"John", "Mary", "John"};

foreach (var student in students.GroupBy(x => x))
{
    Console.WriteLine("{0}: {1}", student.Key, student.Count());
}

Returns:

John: 2
Mary: 1

You can show the ones that have duplicates too:

var dups = students.GroupBy(x => x)
                   .Where(g => g.Count() > 1)
                   .Select(g => g.Key);

foreach (var student in dups)
{
    Console.WriteLine("Duplicate: {0}", student);
}

Returns:

Duplicate: John

Note: You will need to change GroupBy(x => x) depending on what your Student object is of course. In this case, it's just a string.

yamen
  • 15,390
  • 3
  • 42
  • 52
1
var students = new List<string> { "John", "Mary", "John" };
var duplicates = students.GroupBy(x => x)
                         .Select(x => new { Name = x.Key, Count = x.Count() }); 
Asif Mushtaq
  • 13,010
  • 3
  • 33
  • 42