You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VB.NET中基于多对象的GroupBy分组求和问题求助

问题描述

我有如下数据列表:

list1 =  [
   {meal: {id: 1, version: 0}, type: {id: 2, version: 0}, adjCount: 1, systemCount: 0},
   {meal: {id: 1, version: 0}, type: {id: 2, version: 0}, adjCount: 2, systemCount: 0},
   {meal: {id: 2, version: 0}, type: {id: 1, version: 0}, adjCount: 4, systemCount: 0},
   {meal: {id: 2, version: 0}, type: {id: 1, version: 0}, adjCount: 7, systemCount: 0},
]

期望按meal和type对象分组,对adjCount求和,得到结果:

{meal: {id: 1, version: 0}, type: {id: 2, version: 0}, adjCount: 3, systemCount: 0},
{meal: {id: 2, version: 0}, type: {id: 1, version: 0}, adjCount: 11, systemCount: 0}

尝试了以下Linq代码但未得到预期结果:

List.GroupBy(Function(myItem) New MyObject With {.mealTypeId = myItem.Meal.Id, .countTypeId = MyItem.Count.Id}).
Select(Function(g) New With
 {
    .MealTypeId = g.Key.MealTypeId,
    .CountTypeId = g.Key.CountTypeId,
    .AdjustmentCount = g.Sum(Function(i) i.AdjustmentCount),
    .SystemCount = g.Sum(Function(i) i.SystemCount)
 }
修正方案

你的代码存在几个关键问题:

  • 属性名不匹配:原数据类型字段是type,代码里误用了MyItem.Count.Id;原数据计数字段是adjCount,代码里用了AdjustmentCount,导致无法正确取值。
  • 分组键逻辑错误:自定义MyObject作为分组键时,若未重写Equals和GetHashCode实现属性级相等比较,Linq无法识别相同分组。匿名类型会自动实现基于属性的相等判断,更适合做分组键。
  • 输出结构不符:当前输出仅返回ID,而期望结果需要完整的meal和type对象。

修正后的VB.NET Linq代码如下:

list1.GroupBy(Function(item) New With {
    Key .MealId = item.meal.id,
    Key .MealVersion = item.meal.version,
    Key .TypeId = item.type.id,
    Key .TypeVersion = item.type.version
}) _
.Select(Function(g) New With {
    .meal = New With {.id = g.Key.MealId, .version = g.Key.MealVersion},
    .type = New With {.id = g.Key.TypeId, .version = g.Key.TypeVersion},
    .adjCount = g.Sum(Function(i) i.adjCount),
    .systemCount = g.Sum(Function(i) i.systemCount)
})

代码说明

  1. 分组键使用匿名类型,包含meal和type的id与version,确保相同的meal和type被归为同一组。
  2. 投影时重建完整的meal和type对象,完全匹配期望的输出结构。
  3. 直接使用原数据中的字段名adjCount和systemCount,避免字段名不匹配问题。

如果你的数据是强类型实体类,可直接将meal和type对象作为分组键,但需确保这些类正确实现了相等比较逻辑。

内容的提问来源于stack exchange,提问作者Abhi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 06:15:43