2

嗨,我需要在 vb.net 中有 group by 的动态 linq 查询。

我的查询如下。

在第一个查询中,我需要按两列分组,但在第二个查询中,我只需要按一列分组。这取决于用户希望如何查看报告。

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

提前致谢。

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"))
4

1 回答 1

1

正如您从Select子句中看到的那样,您的两个查询的结果不是(匿名)类型兼容的。您最简单的解决方案可能是将您的第二个查询更改为具有第二个冗余或常量组键的内容。

例如

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在需要时忽略。

于 2012-10-15T01:03:31.920 回答