build linq queries dynamically

后端 未结 2 545
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-11 23:53

suppose I have a string list, like

list cols = {\"id\", \"name\", \"position\"}.

This list is generated dynamically, and each

相关标签:
2条回答
  • 2020-12-12 00:22

    You can use Expression Trees to build dynamic Linq queries. Here is an example: http://msdn.microsoft.com/en-us/library/bb882637.aspx

    0 讨论(0)
  • 2020-12-12 00:40

    As Chocoboboy said, System.Linq.Dynamic would help. Unfortunately, this is not included in the .NET framework, but you can download it from the Scott Guthrie's blog. In your case, you need to call Select(string selector) (with the column list hard-coded or sourced from a list). Optionally, my example includes a dynamic Where clause (Where("salary >= 50")):

    List<string> cols = new List<string>(new [] { "id", "name", "position" });
    var employ = new[] { new { id = 1, name = "A", position = "Manager", salary = 100 },
        new { id = 2, name = "B", position = "Dev", salary = 50 },
        new { id = 3, name = "C", position = "Secretary", salary = 25 }
    };
    string colString = "new (id as id, name as name, position as position)";
    //string colString = "new ( " + (from i in cols select i + " as " + i).Aggregate((r, i) => r + ", " + i) + ")";
    var q = employ.AsQueryable().Where("salary >= 50").Select(colString);
    foreach (dynamic e in q)
        Console.WriteLine(string.Format("{0}, {1}, {2}", e.id, e.name, e.position));
    

    However, this approach somehow defeats the purpose of LINQ strongly-typed queries, so I would use it with caution.

    0 讨论(0)
提交回复
热议问题