Linq Lambda GroupBy and OrderBy

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

how can I do this with a lamp

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();
        }
    }
}

Above gives me this.

Key is Apple

---- Grandma Smith

---- Gala

Key - Strawberry

---- Tasty

But as you can see, the price of the Gala is lower than the blacksmith ... what am I doing wrong? Plese help!

+3
source share
3 answers

You group before ordering. In other words, you are organizing groups, not elements within groups.

Try to arrange first.

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

That should work.

+9
source

You tried

var grouped = data.OrderBy(x => x.Price).GroupBy(record => record.Type);
+3
source
var grouped = data.GroupBy(record => record.Type)
.Select(g=>new {g.Key,records=g.OrderBy(r=>r.Price)})  

// at this moment the records are ordered by price (within groupings)

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

// now groups are also ordered by minimum price

0
source

Source: https://habr.com/ru/post/1781787/


All Articles