LINQ & The Dynamic Query or How to get a "Unknown" number of columns?
I have a table with 40 (int) columns and I need to get certain columns depending on user input, sometimes it might be 1 and some oth开发者_如何学运维er times it might be all 40, how can I do this using LINQ?
Use the Dynamic Linq library.
http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx
How many rows is it? It might be simpler to just always fetch all 40 columns and then just ignore the values that you don't need. If that will give performance problems then you can use the Select extension to select the columns you want:
IQueryable<MyResult> myResult;
if (wantColumnFoo) {
myResult = table.Select(x => new MyResult { x.Id, Foo = x.Foo });
} else {
myResult = table.Select(x => new MyResult { x.Id, Foo = null });
}
But that will soon be a lot of work if you need to handle all 40 columns like this.
精彩评论