如何使用vb.net linq通过匿名类型进行分组 [英] how to group by over anonymous type with vb.net linq to object

查看:159
本文介绍了如何使用vb.net linq通过匿名类型进行分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在vb.net中编写一个对对象查询的linq,这是我要实现的C#版本(我正在linqpad中运行它):

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;
}

我对语法不同的分组感到不快(vb在某些地方需要'identifier = expression',以及在求和函子中需要'expression required')

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' )

非常感谢您的帮助!

推荐答案

您可以在VB.NET中创建类型为Object的数组,该数组可以包含任何类型的对象,包括匿名类型.如果您保持相同的字段名称,类型和顺序,编译器将正确推断要使用相同的匿名类型. 我在LinqPad中运行了这段代码,以获得您正在寻找的结果

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

这篇关于如何使用vb.net linq通过匿名类型进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆