チョコボボーイが言ったように、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 クエリの目的に何らかの形で反するため、注意して使用します。