4

Using a linq query, how can i pass parameters into the groupby function? Depend on user selection, it will be grouped differently

 var query = (from to in OrderQuery
                     group to by to.FromDateUtc into groupedDate
                     let grouped = groupedDate.GroupBy(o => o.Name)

I would like to pass different groupby values. Any idea?

Cheers

ove
  • 3,092
  • 6
  • 34
  • 51

2 Answers2

2

Generally speaking, you need different queries for this. The same goes for building up different WHERE or Where(...) clauses based on user selection:

var query = OrderQuery;
if (userSelection == "GroupByName") {
    query = from to in query
            group to by to.FromDateUtc into groupedDate
            let grouped = groupedDate.GroupBy(o => o.Name);
}
else if (userSelection == "GroupBySomethingElse") {
    query = from to in query
            group to by to.FromDateUtc into groupedDate
            let grouped = groupedDate.GroupBy(o => o.SomethingElse);
}

You'll want to prepare as much common logic as possible before you apply the grouping to query. Because LINQ uses deferred execution you can modify query as much as you need before enumerating the result and you will not incur a performance hit.

Yuck
  • 49,664
  • 13
  • 105
  • 135
  • Hmm.. interesting.. This is just 10% of my query. Seems like i need to copy and paste a whole lot :( – ove Apr 24 '12 at 17:02
  • @overule Well, hopefully not. The only parts you'd need to copy & paste would be those that deal with the *differences* in how you're grouping. As I mentioned, you should set up `query` to contain any joins, filtering, sorting before you conditionally apply grouping. – Yuck Apr 24 '12 at 17:05
0

If you are trying to do something like this

SELECT * FROM <TableName> GROUP BY <Column1>,<Column2>

Then, take a look at this post

Group By Multiple Columns

Community
  • 1
  • 1
Rahul
  • 76,197
  • 13
  • 71
  • 125