C# 将具有相同名称的项目列表分组,并在“返回所有”列中添加值
我有数据库中的项目列表,如下所示:C# 将具有相同名称的项目列表分组,并在“返回所有”列中添加值,c#,model-view-controller,C#,Model View Controller,我有数据库中的项目列表,如下所示: Category ItemName Quantity Location Commputing Mouse 2 store1 Printer Zebra P4T 5 store2Bank5 Commputing Mouse 4 store1 Printer ZT zebra 2 store1Bank2 Pr
Category ItemName Quantity Location
Commputing Mouse 2 store1
Printer Zebra P4T 5 store2Bank5
Commputing Mouse 4 store1
Printer ZT zebra 2 store1Bank2
Printer ZT zebra 1 store1Bank2
FarmTool FieldBoot 12 Store1Floor2
FarmTool FieldBoot 12 Store1Floor2
[2] 因此,我希望得到与以下名称相同的项的总和:
Category ItemName Quantity Location
Commputing Mouse 6 store1
Printer Zebra P4T 5 store2Bank5
FarmTool FieldBoot 24 Store1Floor2
Printer ZT zebra 3 store1Bank2
我的代码如下:
IEnumerable<Item> items = db.Items;
var da = items
.GroupBy(d => d.ItemName)
.Select(g => new {
Key = g.Key, quantity = g.Sum(s => s.ItemQty),
Name = g.First().Location,
ItemName = g.First().ItemName,
Category = g.First().Category
})
.ToList();
return View();
IEnumerable items=db.items;
var da=项目
.GroupBy(d=>d.ItemName)
.选择(g=>new{
Key=g.Key,quantity=g.Sum(s=>s.ItemQty),
Name=g.First().Location,
ItemName=g.First().ItemName,
Category=g.First().Category
})
.ToList();
返回视图();
您可以尝试以下方法。基本上,您使用作为分组键
类别
和项目名称
IEnumerable<Item> items = db.Items;
var da = items.GroupBy(x=> new { x.Category, x.ItemName })
.Select(g => new {
Category = g.Key.Category,
ItemName = g.Key.ItemName,
Quantity = g.Sum(s => s.ItemQty),
Location = g.First().Location}).ToList();
IEnumerable items=db.items;
var da=items.GroupBy(x=>new{x.Category,x.ItemName})
.选择(g=>new{
类别=g.Key.Category,
ItemName=g.Key.ItemName,
数量=总数量(s=>s.ItemQty),
Location=g.First().Location}).ToList();
非常感谢您的帮助。那么,我应该传递给视图什么呢?我是否必须这样做:返回视图(da)