Search code examples
c#entity-frameworklinqlinq-to-entitiesdynamic-linq-core

How to GroupBy nothing in Dynamic Linq Core


I'm creating some dynamic linq statement for user to decide what to group by. However, when the user input nothing I'd like the query to group by 'nothing', as in just output the query result as if there was no groupby. Something similar to this answer here but using Dynamic Linq Core.

var query = db.II_POLICY_AND_COVERAGE
                    .Where(x => (x.date>= settings.StartDate && x.date<= settings.EndDate))
                    .GroupBy(user_groupby_input_string);

                if (user_defined_calc_method.Equals("Total"))
                {
                    query = query.Select("new(Key as name, Sum(money_column) as value)");
                }
                else if (user_defined_calc_method.Equals("Count"))
                {
                    query = query.Select("new(Key as name, Count() as value)");
                }

For example, if user_groupby_input_string is "gender", the query will groupby the gender column. If user_groupby_input_string is "" or null, the query will ignore the groupby line and just do sum or count the whole dataset.


Solution

  • This case is specially handled by LINQ Translator when you GroupBy by constant, for example 1. LINQ Translator will remove grouping and make simple plain SQL with aggregation functions.