ASPNET MVC+ EF如何实现分组获取每组的和值
在ASP.NET MVC中使用Entity Framework(EF)实现分组获取每组的和值的方法如下:
- 创建一个包含分组和和值的视图模型类,例如GroupSumViewModel:
public class GroupSumViewModel
{
public string Group { get; set; }
public int Sum { get; set; }
}
- 在控制器中创建一个动作方法,例如GetGroupSum,用于获取分组和值的列表:
public ActionResult GetGroupSum()
{
var groupSumList = db.Items
.GroupBy(i => i.Group)
.Select(g => new GroupSumViewModel
{
Group = g.Key,
Sum = g.Sum(i => i.Value)
})
.ToList();
return View(groupSumList);
}
- 在视图中使用循环来显示分组和值的列表:
@model List<GroupSumViewModel>
<table>
<tr>
<th>Group</th>
<th>Sum</th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>@item.Group</td>
<td>@item.Sum</td>
</tr>
}
</table>
这样,当访问GetGroupSum动作方法时,将会返回分组和值的列表,并在视图中显示出来
原文地址: http://www.cveoy.top/t/topic/hNwG 著作权归作者所有。请勿转载和采集!