Linq Lambda GroupBy and OrderBy

Ravi picture Ravi · Dec 23, 2010 · Viewed 13.5k times · Source

I would like to Group by and then order the items within the group.

how do i do it with lamda,

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var data = new[]
                  {
                      new { Name="Tasty", Type="Strawberries", isAvail=true, Price=1.90m, Quantity=20 },

                    new { Name="Granny Smith", Type="Apple", isAvail=false, Price=0.80m, Quantity=7 },
                    new { Name="Gala", Type="Apple", isAvail=true, Price=0.75m, Quantity=10 }

                  };

            var grouped = data.GroupBy(record => record.Type).OrderBy(x => x.Min(y => (Decimal)y.Price));

            foreach (var group in grouped)
            {
                Console.WriteLine("Key {0}", group.Key);

                foreach (var item in group)
                {
                    Console.WriteLine("\t{0}", item.Name);
                }
            }
            Console.ReadLine();
        }
    }
}

the Above gives me this..

Key - Apple

----Granny Smith

----Gala

Key - Strawberries

----Tasty

But as you can see the price of Gala is lower than Granny smith... what am i doing wrong? Plese help!

Answer

Kirk Broadhurst picture Kirk Broadhurst · Dec 23, 2010

You are Grouping before you are Ordering. In other words, you are ordering the groups rather than the items within the groups.

Trying ordering first.

var grouped = data.OrderBy(x => x.Price).GroupBy(record => record.Type); 

This should work.