简体   繁体   中英

Linq - SQL passing parameters into GroupBy()

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM