提问者:小点点

如何选择不在groupby中的属性


我正在尝试选择一些不在我的分组依据中的属性。这可能吗?

var r = from w in drinks.ToList()
  group w by new{
   w.DrinkId
  } into wGroup
  select new DrinksValue(){
   DrinkId = wGroup.DrinkId,
   CatId = // trying to pull from wGroup???
   Lasting = // trying to pull from wGroup???
   DrinkTypes = wGroup.Select( x => new DrinkAttributes { Taste = wGroup.Key.Flavor, Benefit = wGroup.Sum(x => x.Value)
  }).ToList()
};

如何从drinks.tolist()中获取CatId和持久属性?

如果我将它们添加到组中,就像w.drinkid、w.flavor、w.value、w.catid、w.lenerate,那么我的结果就会混乱。

我可以使用.sum获得其他属性,如value,但这些属性不是计算值。

数据示例:

DrinkId | CatId | Lasting | Flavor | Value
------------------------------------------
1     2        5.1      orange   11.0
1     2        5.1      blue     09.0
1     2        6.0      red      10.0
2     3        6.0      red      10.0
2     3        6.0      yellow   01.0

希望将结果按如下方式分组:

{
  "DrinkId": 1,
  "CatId": 2,
  "Lasting": 5.1,
  "DrinkTypes": [{ Taste: orange,  Benefit: 11.0}, {Taste: blue,  Benefit: 09.0}, {Taste: red,  Benefit: 10.0}]
}

共2个答案

匿名用户

此查询应起作用:

var query = 
    from w in drinks
    group w by new { w.DrinkId, w.CatId, w.Lasting } into wGroup
    select new DrinksValue
    {
        DrinkId = wGroup.Key.DrinkId,
        CatId = wGroup.Key.CatId,
        Lasting = wGroup.Key.Lasting,
        DrinkTypes = wGroup.Select(x => new DrinkAttributes 
            { Taste = x.Flavor, Benefit = x.Value }
            ).ToList()          
    }
};

var r = query.ToList()

匿名用户

通过将这些属性包含在groupby中,您应该能够获得所需的结果,至少您的示例数据显示的DrinkId、CatId和Deneral的值总是相同的。

var r = from w in drinks
  group w by new{
   w.DrinkId,
   w.CatId,
   w.Lasting
  } into wGroup
  select new DrinksValue(){
   DrinkId = wGroup.DrinkId,
   CatId =  wGroup.CatId
   Lasting = wGroup.Lasting,
   DrinkTypes = wGroup.Select( x => new DrinkAttributes { Taste = wGroup.Key.Flavor, Benefit = wGroup.Sum(x => x.Value)}).ToList()
};