我有一个正确存储在列表<>中的ID列表.我现在需要对此列表进行分组,并获得按降序排序的发生次数的计数.
例:
List<string> aryIDs = new List<string>; aryIDs.Add("1234"); aryIDs.Add("4321"); aryIDs.Add("3214"); aryIDs.Add("1234"); aryIDs.Add("4321"); aryIDs.Add("1234");
会产生:
"1234",3 "4321",2 "3214",1
这在Tsql中很容易,但如果可能,我想避免服务器往返,不必要的表等.
提前致谢.
更新:对于Ralph Shillington的回答如下:
Dim result = From id In aryIDs _ Group id By id Into Group _ Order By Group.Count() Descending _ Select id,Count = Group.Count() result.Dump()
解决方法
List<string> aryIDs = new List<string>(); aryIDs.Add("1234"); aryIDs.Add("4321"); aryIDs.Add("3214"); aryIDs.Add("1234"); aryIDs.Add("4321"); aryIDs.Add("1234"); var result = from id in aryIDs group id by id into g orderby g.Count() descending select new { Id=g.Key,Count=g.Count() }; result.Dump();
剪切并粘贴到LinqPad,你应该很好去.
也可以使用Lambda表达式来写:
aryIDs.GroupBy (id => id).OrderByDescending (id => id.Count()).Select(g => new { Id=g.Key,Count=g.Count()}).Dump();