动态linq查询字符串不起作用

时间:2018-06-28 08:40:06

标签: .net asp.net-mvc linq

  public ActionResult Query(List<string> sortable_bot, List<string> sortable_top)
    {
        string gro = "from st in context.Customers";

        for (int i = 0; i < sortable_top.Count; i++)
        {
            gro += " group st by st." + sortable_top[i].ToString();
        }

        string into = " into g select new Group2() { Key = g.Key, Count = g.Count() }";
        gro += into;

        using (var context = new NwContext())
        {
            *var que = gro;
            return View(que.ToList());
        }
    }

我在星号处添加了一个断点,并且gro字符串等于from st in context.Customers group st by st.Country into g select new Group2() { Key = g.Key, Count = g.Count() }

但是这不起作用。如果我直接像这样写var que= from st in context.Customers group st by st.Country into g select new Group2() { Key = g.Key, Count = g.Count() };就行了。

2 个答案:

答案 0 :(得分:2)

使用System.Linq.Dynamic.Core(具有nuget)的扩展示例:

给出:

public class KeyCount
{
    public dynamic Key { get; set; }
    public int Count { get; set; }
}

然后您可以:

public KeyCount[] Query(List<string> sortable_top)
{
    string gro = string.Join(",", sortable_top);

    using (var context = new MyDbContext())
    {
        IQueryable result = context.Customers;
        result = result.GroupBy("new (" + gro + ")", "it");
        IEnumerable<KeyCount> result2 = result.Select<KeyCount>("new (it.Key, it.Count() as Count)") ;
        return result2.ToArray();
    }
}

请注意我是如何Select KeyCount到半静态类型的对象(Key)的,其中dynamic仍然是Count(因为最后的列数用于分组的是在运行时动态选择的),而intTuple<dynamic, int>

只有两个字段,甚至可以使用public Tuple<dynamic, int>[] Query(List<string> sortable_bot, List<string> sortable_top) { string gro = string.Join(",", sortable_top); using (var context = new MyDbContext()) { IQueryable result = context.Products; result = result.GroupBy("new (" + gro + ")", "it"); var result2 = result.Select<Tuple<dynamic, int>>("new (it.Key, it.Count() as Count)"); return result2.ToArray(); } }

{{1}}

答案 1 :(得分:0)

System.Dynamic.Linq无法解析整个linq查询。它可以解析字符串以创建lambda表达式。

例如,此查询与您的查询类似:

var que= from st in context.Customers 
group st by st.Country into g 
select new { Key = g.Key, Count = g.Count() };

可以用System.Dynamic.Linq重写:

var que = context.Customers.
  .GroupBy("Country", "it")
  .Select("new (it.Key as Key, it.Count() as Count)");

然后您可以读取如下结果:

foreach (dynamic group in que)
{
    Console.WriteLine(group.Key + " " + group.Count);
    // Populate collection of Group2
}

要按多列分组,您需要构造两个字符串(一个用于GroupBy,一个用于Select),并像这样使用它:

var que = context.Customers.
  .GroupBy("new ( it.Country, it.City)", "it")
  .Select("new (it.Country, it.City, it.Count() as Count)");