I have a list of ids properly stored in a List<>. I now need to Group this list and get a count of the number of occurrences sorted descending.
Example:
List<string> aryIDs = new List<string>;
aryIDs.Add("1234");
aryIDs.Add("4321");
aryIDs.Add("3214");
aryIDs.Add("1234");
aryIDs.Add("4321");
aryIDs.Add("1234");
Would Produce:
"1234", 3
"4321", 2
"3214", 1
This would be easy in TSQL, but I would like to avoid the server roundtrip, unnecessary tables, etc. if possible.
Thanks in advance.
Update: The VB.NET conversion for Ralph Shillington's answer below:
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();
Cut and paste that into LinqPad and you should be good to go.
It could also be written using Lambda expressions as:
aryIDs.GroupBy (id => id).OrderByDescending (id => id.Count()).Select(g => new { Id=g.Key, Count=g.Count()}).Dump();
How about 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() };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With