5

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!

yoozer8
  • 7,361
  • 7
  • 58
  • 93
Ravi
  • 51
  • 1
  • 1
  • 2

3 Answers3

11

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.

Kirk Broadhurst
  • 27,836
  • 16
  • 104
  • 169
3

Have you tried

var grouped = data.OrderBy(x => x.Price).GroupBy(record => record.Type);
Adriaan Stander
  • 162,879
  • 31
  • 289
  • 284
1
var grouped = data.GroupBy(record => record.Type)
.Select(g=>new {g.Key,records=g.OrderBy(r=>r.Price)})  

// at this point records are ordered by price (inside groupings)

.OrderBy(x => x.records.Min(y => (Decimal)y.Price))

// now groupings are ordered by min price as well

Alexander Taran
  • 6,655
  • 2
  • 39
  • 60