Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
614 views
in Technique[技术] by (71.8m points)

build linq queries dynamically

suppose I have a string list, like

list<string> cols = {"id", "name", "position"}.

This list is generated dynamically, and each one in this list represents a column name in a database table.

what I want to do is create a linq query dynamically which returns these columns only.

var q = from e in employ
        select new {
          id = id,
          name = name,
          position = position
};

How can I generate a query like that based on the input column lists?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...