我有一个表,名称为Fuel,数据显示在表中,如
Name | OrderDate | Qty
H&S1 | 1/1/2008 | 100
H&S1 | 1/2/2008 | 200
H&S1 | 2/2/2008 | 350
H&S2 | 2/28/2008 | 220
H&S2 | 3/12/2008 | 250
H&S2 | 3/15/2008 | 2150
,我想在“ 查看
”上显示“结果”Name| Jan- 2008 | Feb- 2008 | Mar - 2008| Total
1 | 100 | 350 | 250 | 700
2 | 200 | 220 | 2150 | 2170
和 IActionResult 是
public IActionResult GetRes()
{
List<CustData> myList = GetCustData();
var query = myList
.GroupBy(c => c.Name)
.Select(g => new {
CustId = g.Key,
Jan = g.Where(c => c.OrderDate.Month == 1).Sum(c => c.Qty),
Feb = g.Where(c => c.OrderDate.Month == 2).Sum(c => c.Qty),
March = g.Where(c => c.OrderDate.Month == 3).Sum(c => c.Qty)
});
return View(myList);
}
现在我想在视图上显示此数据 谁能指导我如何在View上显示这种格式。 像这样
Name| Jan- 2008 | Feb- 2008 | Mar - 2008| Total
1 | 100 | 350 | 250 | 700
2 | 200 | 220 | 2150 | 2170
答案 0 :(得分:1)
您可以为此创建一个视图模型并通过引入一个新属性进行聚合:
public class SomeVM
{
public int CustId { get; set; }
public int Jan { get;set; }
public int Feb { get;set; }
public int Mar { get;set; }
public int Total { get { return Jan + Feb + Mar;} }
}
,然后在您的linq查询中:
.Select(g => new SomeVM {
CustId = g.Key,
Jan = g.Where(c => c.OrderDate.Month == 1).Sum(c => c.Qty),
Feb = g.Where(c => c.OrderDate.Month == 2).Sum(c => c.Qty),
March = g.Where(c => c.OrderDate.Month == 3).Sum(c => c.Qty)
});
您甚至可以使用GroupBy
属性上的Month
来改善linq查询。
更好的方法是为月份引入一个枚举:
public class SomeVM
{
public int CustId { get; set; }
public List<FuelQuantity> FuelQuantities { get; set; }
public int Total { get; set; }
SomeVM()
{
FuelQuantities = new List<FuelQuantity>();
}
}
和FuelQuantity看起来像:
public class FuelQuantity
{
public FuelMonth Month { get; set; }
public int Quantity { get; set; }
}
您的FuelMonth如下所示:
public enum FuelMonth : int
{
January = 1,
February = 2,
..........
..........
}
还需要调整您的linq查询以填充该集合,然后可以填充总计。