2012-04-23 45 views

回答

4
string[] names = { "ghj", "def", "abc", "def", "abc", "abc" }; 

IEnumerable<string> query = names 
    .GroupBy(s=>s) // groups identical strings into an IGrouping 
    .OrderByDescending(group => group.Count()) // IGrouping is a collection, so you can count it 
    .Select(group=>group.Key); // IGrouping has a Key, which is the thing you used to group with. In this case group.Key==group.First()==group.skip(1).First() ... 
2

如果你想獲得由事件下令不同列表,使用組方:

var query = foo.GroupBy(xx => xx) 
       .OrderByDescending(gg => gg.Count()) 
       .Select(gg => gg.Key); 
// on your input returns: 
// abc 
// def 
// ghj 
+0

我是扔掉的變量雙字母語法的忠實粉絲,雖然我有自其他人不喜歡他們以來一直試圖擺脫這種習慣。很高興看到我並不孤單 – HugoRune 2012-04-23 16:00:20