How to count duplicate in linq?

asp.net, c#, linq

Solution

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`.

Problem

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'?

Original source

Related problems