2012-05-21 39 views

回答

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
var students = new List<string> { "John", "Mary", "John" }; 
var duplicates = students.GroupBy(x => x) 
         .Select(x => new { Name = x.Key, Count = x.Count() });