2
可能重複:
How to Count Duplicates in List with LINQ如何在linq中統計重複?
任何想法,你怎麼指望在LINQ重複。假設我有一個Student對象列表 ,我想找到名爲'John'的學生的數量?
可能重複:
How to Count Duplicates in List with LINQ如何在linq中統計重複?
任何想法,你怎麼指望在LINQ重複。假設我有一個Student對象列表 ,我想找到名爲'John'的學生的數量?
您可以使用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
。
var students = new List<string> { "John", "Mary", "John" };
var duplicates = students.GroupBy(x => x)
.Select(x => new { Name = x.Key, Count = x.Count() });