2

可能的重复:
如何使用 LINQ 计算列表中的重复

知道如何计算 linq 中的重复项。假设我有一个学生对象列表,我想在其中找到名为“约翰”的学生数量?

4

2 回答 2

9

您可以使用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());
}

回报:

John: 2
Mary: 1

您也可以显示那些有重复的:

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);
}

回报:

Duplicate: John

注意:您当然需要GroupBy(x => x)根据您的Student对象进行更改。在这种情况下,它只是一个string.

于 2012-05-21T03:31:42.243 回答
1
var students = new List<string> { "John", "Mary", "John" };
var duplicates = students.GroupBy(x => x)
                         .Select(x => new { Name = x.Key, Count = x.Count() }); 
于 2012-05-21T04:43:30.367 回答