how to group by over anonymous type with vb.net linq to object

风流意气都作罢 提交于 2019-12-11 04:54:00

问题


I'm trying to write a linq to object query in vb.net, here is the c# version of what I'm trying to achieve (I'm running this in linqpad):

void Main()
{
 var items = GetArray(
        new {a="a",b="a",c=1}
        , new {a="a",b="a",c=2}
        , new {a="a",b="b",c=1}
    );

 (
  from i in items 
  group i by new {i.a, i.b} into g
  let p = new{ k = g, v = g.Sum((i)=>i.c)}
  where p.v > 1
  select p
 ).Dump();
}
// because vb.net doesn't support anonymous type array initializer, it will ease the translation
T[] GetArray<T>(params T[] values){
  return values;
}

I'm having hard time with either the group by syntax which is not the same (vb require 'identifier = expression' at some places, as well as with the summing functor with 'expression required' )

Thanks so much for your help!


回答1:


You can create an array of type Object in VB.NET that can contain objects of any type, including anonymous types. The compiler will correctly infer that the same anonymous type is to be used provided you keep the same field name, types, and order of fields. I ran this code in LinqPad to get the results you are looking

 Dim items As Object() = { _
               New With {.a="a",.b="a",.c=1}, _
               New With {.a="a",.b="a",.c=2}, _
               New With {.a="a",.b="b",.c=1} _
            }
    Dim myQuery = From i In items _
             Group By i.a, i.b into g  = Group _
             let p = New With { .k = g, .v = g.Sum(Function(i) i.c)} _
          where p.v > 1 _
          select p
myQuery.Dump


来源:https://stackoverflow.com/questions/2336466/how-to-group-by-over-anonymous-type-with-vb-net-linq-to-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!