我有一个正确存储在List<>中的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的VB.NET转换如下:
Dim result = From id In aryIDs _
Group id By id Into Group _
Order By Group.Count() Descending _
Select id, Count = Group.Count()
result.Dump()
答案 0 :(得分:19)
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();
答案 1 :(得分:1)
http://msdn.microsoft.com/en-us/vcsharp/aa336747#countGrouped:
怎么样?List<Customer> customers = GetCustomerList();
var orderCounts =
from c in customers
select new { c.CustomerID, OrderCount = c.Orders.Count() };