suppose I have a string list, like
list cols = {\"id\", \"name\", \"position\"}.
This list is generated dynamically, and each
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 cols = new List(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.