ASP.NET MVC 使用 EF 实现分组统计 - 每组和值获取
在 ASP.NET MVC 中,可以使用 Entity Framework (EF) 来实现分组获取每组的和值。\n\n首先,你需要定义一个包含分组和和值的视图模型类,例如:\n\ncsharp\npublic class GroupSumViewModel\n{\n public string Group { get; set; }\n public int Sum { get; set; }\n}\n\n\n然后,在控制器中,你可以使用 LINQ 查询来获取每组的和值。假设你有一个名为 "Item" 的实体类,其中包含一个 "Group" 属性表示分组,一个 "Value" 属性表示值,你可以使用以下代码:\n\ncsharp\npublic ActionResult Index()\n{\n var groupSums = db.Items\n .GroupBy(i => i.Group)\n .Select(g => new GroupSumViewModel\n {\n Group = g.Key,\n Sum = g.Sum(i => i.Value)\n })\n .ToList();\n\n return View(groupSums);\n}\n\n\n在上述代码中,我们首先使用 GroupBy 方法按照 "Group" 属性进行分组,然后使用 Select 方法将每个分组的和值转换为 GroupSumViewModel 对象,并将结果存储在 groupSums 变量中。\n\n最后,将 groupSums 传递给视图,以便在视图中显示每组的和值。在视图中,你可以使用 foreach 循环遍历 groupSums 并显示每个分组的和值:\n\nhtml\n@foreach(var groupSum in Model)\n{\n <p>@groupSum.Group: @groupSum.Sum</p>\n}\n\n\n通过以上步骤,你可以实现分组获取每组的和值。
原文地址: https://www.cveoy.top/t/topic/pwDx 著作权归作者所有。请勿转载和采集!