Linq Lambda GroupBy 和 OrderBy
我想分组,然后对组内的项目进行排序。
我如何用 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 - 苹果
----Granny Smith
----Gala
Key - 草莓
----Tasty
但正如你所看到的,Gala 的价格比 Granny 低史密斯……我做错了什么?请帮忙!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您在订购之前先进行分组。换句话说,您对组进行排序,而不是对组内的项目进行排序。
先尝试订购。
这应该有效。
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.
This should work.
你尝试过吗
Have you tried
// 此时记录按价格排序(在分组内)
// 现在分组也按最低价格排序
// at this point records are ordered by price (inside groupings)
// now groupings are ordered by min price as well