任何想法你如何计算linq中的副本。假设我有一个Student对象列表 在哪里我想找到称为'约翰'的学生数量?
答案 0 :(得分: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
。
答案 1 :(得分:1)
var students = new List<string> { "John", "Mary", "John" };
var duplicates = students.GroupBy(x => x)
.Select(x => new { Name = x.Key, Count = x.Count() });