How to write this Linq SQL as a Dynamic Query (using strings)?

后端 未结 2 1427
别跟我提以往
别跟我提以往 2021-01-02 21:36

Skip to the \"specific question\" as needed. Some background:

The scenario: I have a set of products with a \"drill down\" filter (Query Object) p

2条回答
  •  天命终不由人
    2021-01-02 22:10

    I'm not sure how to do this using Query syntax (as above), but using Method syntax, we can use an Expression

    using System;
    using System.Linq;
    using System.Linq.Expressions;
    
    namespace LinqResearch
    {
        public class Program
        {
            [STAThread]
            static void Main()
            {
                string columnToGroupBy = "Size";
    
                // generate the dynamic Expression>
                ParameterExpression p = Expression.Parameter(typeof(Product), "p");
    
                var selector = Expression.Lambda>(
                    Expression.Property(p, columnToGroupBy),
                    p
                );
    
                using (LinqDataContext dataContext = new LinqDataContext())
                {
                    /* using "selector" caluclated above which is automatically 
                    compiled when the query runs */
                    var results = dataContext
                        .Products
                        .GroupBy(selector)
                        .Select((group) => new { 
                            Key = group.Key, 
                            Count = group.Count()
                        });
    
                    foreach(var result in results)
                        Console.WriteLine("{0}: {1}", result.Key, result.Count);
                }
    
                Console.ReadKey();
            }
        }
    }
    

提交回复
热议问题