LINQ Dynamic Query with group by and string variable

时间:2018-02-01 18:21:07

标签: c# sql linq

I want to create a dynamic query with LINQ-to-SQL and everything works except for one thing: group by. I looked at the other questions but haven't found a reason so far why it does not work.

I use using System.Linq.Dynamic; with the following query (that works):

int numberOfRankedItems = 3;

string minMaxChoice = "max";
string orderBy = "";
if (minMaxChoice == "max")
{
    orderBy = "queryGroup.Sum(row => row.POSITIONVALUE) descending";
} else if (minMaxChoice == "min")
{
    orderBy = "queryGroup.Sum(row => row.POSITIONVALUE) ascending";
}

string minMaxFeatureColumnName = "BRANDNAME";
string selectMinMaxFeature = "new { minMaxFeature = queryGroup.Key." + minMaxFeatureColumnName + ", sumPosition = queryGroup.Sum(row => row.POSITIONVALUE)}";

var query = (from tableRow in Context.xxx
                where /* some filters */
                group tableRow by tableRow.BRANDNAME into queryGroup
                orderby orderBy
                select selectMinMaxFeature).Take(numberOfRankedItems).ToList();

The use of variables for orderby and select works fine, but for group by not no matter what I try to replace with a variable. The query actually works if I e.g. use a variable instead of tableRow.BRANDNAME but the query returns the wrong result. The goal is to be able to set the column for the grouping dynamically.

Ideas?

Thanks

Edit: there seem to be multiple issues also with the other variables. So I generalize the question a bit: how can I generalize the following query in terms of

  1. The column to group by
  2. The column to order by + ASC or DESC
  3. In the select statement the columnname of the first statement (BRANDNAME)

Here is the query:

var query = (from tableRow in ctx.xxx
                where /* filter */
                group tableRow by new { tableRow.BRANDNAME } into queryGroup
                orderby queryGroup.Sum(row => row.POSITIONVALUE) descending
                select new { minMaxFeature = queryGroup.Key.BRANDNAME, sumPosition = queryGroup.Sum(row => row.POSITIONVALUE) }).Take(numberOfRankedItems).ToList();

Would be great without expression trees ;)

1 个答案:

答案 0 :(得分:0)

我现在已经详细阐述了这个问题的解决方案:

解决方案使用之前bash允许现在设置某些变量。最后它返回一个字典。

using System.Linq.Dynamic;