Linq Dynamic Group By

时间:2012-10-13 08:56:22

标签: vb.net linq dynamic group-by

嗨我需要动态linq查询,它在vb.net中有分组。

我的查询如下。

在第一个查询中,我需要按两列进行分组,但在第二个查询中,我只需要按一列进行分组。它取决于用户想要查看报告的方式。

如何根据用户选择在运行时生成这些查询?

提前致谢。

Dim query = From r In dtString.AsEnumerable
        Group r By Key0 = r.Field(Of String)("country"),
                   Key1 = r.Field(Of String)("region") Into Group
        Select Key0, Key1,
               DebitTotal = Group.Sum(Function(r) r.Field(Of Decimal)("debit")),
               CreditTotal = Group.Sum(Function(r) r.Field(Of Decimal)("credit"))


Dim query = From r In dtString.AsEnumerable
        Group r By Key0 = r.Field(Of String)("country") Into Group
        Select Key0
               DebitTotal = Group.Sum(Function(r) r.Field(Of Decimal)("debit")),
               CreditTotal = Group.Sum(Function(r) r.Field(Of Decimal)("credit"))

1 个答案:

答案 0 :(得分:1)

从您的Select子句中可以看出,两个查询的结果并非(匿名)类型兼容。您最简单的解决方案可能是将第二个查询更改为具有第二个冗余或常量组密钥的内容。

E.g。

query = From r In dtString.AsEnumerable
    Group r By Key0 = r.Field(Of String)("country"),
               Key1 = r.Field(Of String)("country") Into Group
    Select Key0, Key1,
           DebitTotal = Group.Sum(Function(r) r.Field(Of Decimal)("debit")),
           CreditTotal = Group.Sum(Function(r) r.Field(Of Decimal)("credit"))

query = From r In dtString.AsEnumerable
    Group r By Key0 = r.Field(Of String)("country"),
               Key1 = "ignored" Into Group
    Select Key0, Key1,
           DebitTotal = Group.Sum(Function(r) r.Field(Of Decimal)("debit")),
           CreditTotal = Group.Sum(Function(r) r.Field(Of Decimal)("credit"))

(未测试的)

然后,您必须在需要时调整结果显示以忽略key1