user1645334
user1645334

Reputation: 89

Linq Dynamic Group By

Hi i need dynamic linq queries which has group by in vb.net.

My queries are as following.

In first query i need to group by two columns, but in second i need to group by just one column. It depens on how user wants to see the report.

How can i produce these queries on runtime according to the user choices?

Thanks in advance.

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

Upvotes: 2

Views: 1724

Answers (1)

Mark Hurd
Mark Hurd

Reputation: 10931

As you can see from your Select clauses, the result of your two queries are not (anonymous) type compatible. Your simplest solution may be to alter your second query to something that does have a second redundant or constant group key.

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

or

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

(untested)

Then you'll have to adjust your result display to ignore key1 when required.

Upvotes: 1

Related Questions