Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ: Order By Count of Unique Items in List<string>

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()
like image 586
Brad M Avatar asked Feb 08 '11 17:02

Brad M


2 Answers

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();
like image 153
Ralph Shillington Avatar answered Nov 16 '22 05:11

Ralph Shillington


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() };
like image 1
Shan Plourde Avatar answered Nov 16 '22 05:11

Shan Plourde