我想要分组依据,然后对组中的项目进行排序。
我该如何使用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();
}
}
}上面的代码给了我这个..
Key - Apple
-史密斯奶奶
-Gala
关键-草莓
-可口
但如你所见,Gala的价格比史密斯奶奶要低..。我做错了什么?请帮帮我!
发布于 2010-12-23 15:12:43
在订购之前,您正在进行分组。换句话说,您是对组进行排序,而不是对组中的项目进行排序。
请先尝试订购。
var grouped = data.OrderBy(x => x.Price).GroupBy(record => record.Type); 这应该是可行的。
发布于 2010-12-23 15:15:12
你试过了吗?
var grouped = data.OrderBy(x => x.Price).GroupBy(record => record.Type);发布于 2010-12-23 15:14:56
var grouped = data.GroupBy(record => record.Type)
.Select(g=>new {g.Key,records=g.OrderBy(r=>r.Price)}) //此时记录按价格排序(分组内)
.OrderBy(x => x.records.Min(y => (Decimal)y.Price))//现在分组也按最低价格排序
https://stackoverflow.com/questions/4516567
复制相似问题