正如Chocoboboy所说,System.Linq.Dynamic
会有所帮助。不幸的是,这不包含在 .NET 框架中,但您可以从 Scott Guthrie 的博客下载它。在您的情况下,您需要调用Select(string selector)
(使用硬编码的列列表或从列表中获取)。可选地,我的示例包括一个动态Where
子句 ( 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));
但是,这种方法在某种程度上违背了 LINQ 强类型查询的目的,所以我会谨慎使用它。