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

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


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 aryIDsgroup id by id into gorderby g.Count() descendingselect 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() };