Reputation: 51
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!
Upvotes: 5
Views: 15467
Reputation: 166506
Have you tried
var grouped = data.OrderBy(x => x.Price).GroupBy(record => record.Type);
Upvotes: 3
Reputation: 6725
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
Upvotes: 1
Reputation: 28728
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.
Upvotes: 11