我是C#和LINQ的新手,我正在使用Northwind数据库。我的视图显示了数据库中的所有订单而没有订购。我想根据联系人姓名(客户)和按字母顺序显示订单:例如,AVARIA以及该客户的所有订单。等等...
我想要这样的事情:
AVARIA
ORDER 1 OF AVARIA FROM DATABASE WITH ITS DETAILS
ORDER 2 OF AVARIA FROM DATABASE WITH ITS DETAILS
ORDER 3 OF AVARIA FROM DATABASE WITH ITS DETAILS
BECUA
ORDER 1 OF BECUA FROM DATABASE WITH ITS DETAILS
ORDER 2 OF BECUA FROM DATABASE WITH ITS DETAILS
and so on...
因为这显示了来自数据库的所有订单,没有任何订购,例如第一行中的客户X和订单,然后客户Y,然后客户X再次订购,依此类推。我试过这个:
public ActionResult Index()
{
var orders = db.Orders.Include(o => o.Customer).Include(o => o.Employee).Include(o => o.Shipper);
var list = orders.OrderBy(x => x.Customer.ContactName);
return View(list.ToList());
}
但它引发了以下异常:
类型的例外 ' System.Data.Entity.Core.EntityCommandExecutionException'发生在 EntityFramework.SqlServer.dll但未在用户代码中处理
视图效果很好。
请帮忙。
答案 0 :(得分:0)
你可以使用group by和orderby。样品:
class Program
{
class grpitem
{
public string groupCode;
public string item;
}
static List<grpitem> list = new List<grpitem>()
{
new grpitem() {groupCode="3", item="b"},
new grpitem() {groupCode="1", item="b"},
new grpitem() {groupCode="3", item="c"},
new grpitem() {groupCode="2", item="b"},
new grpitem() {groupCode="2", item="a"},
new grpitem() {groupCode="2", item="c"},
new grpitem() {groupCode="1", item="a"},
new grpitem() {groupCode="3", item="a"},
new grpitem() {groupCode="3", item="d"}
};
static void Main(string[] args)
{
IEnumerable<grpitem> ordered = list.GroupBy(grp => grp.groupCode)
.SelectMany(g => g.OrderBy(grp => grp.item)).OrderBy(g => g.groupCode);
foreach(grpitem g in ordered)
Console.WriteLine("groupCode:{0} item:{1}",g.groupCode,g.item);
Console.ReadLine();
}
}
输出:
groupCode:1 item:a
groupCode:1 item:b
groupCode:1 item:c
groupCode:1 item:d
groupCode:2 item:a
groupCode:2 item:b
groupCode:3 item:a
groupCode:3 item:b
groupCode:3 item:c
答案 1 :(得分:0)
您可以使用GroupBy(...)
public ActionResult Index()
{
var orders = db.Orders.Include(o => o.Customer).Include(o => o.Employee).Include(o => o.Shipper);
var groupedOrders = orders.GroupBy(o => Customer.Name, o => o);
// grouped orders is IEnumerable<string, IEnumerable<Order>>
return View(groupedOrders);
}