I have a web page where user can specify their query by click a set of DropDownList. Now I want build my sql query base on user's input. I used System.Linq.Expressions to do this.
public static IEnumerable<T> FilterTable<T>(List<Filter> filters, Table<T> table) where T : class
{
int top;
IEnumerable<T> query;
if (filters == null || filters.Count == 0)
{
query = table;
}
else
{
Func<T, bool> lamda = Build<T>(filters, out top);
if (top > 0)
{
query = table.Where(lamda).Take(top);
}
else
{
query = table.Where(lamda);
}
}
return query;
}
This approach does work. But it is slow since IIS first fetch all data from db server, then apply the where clause. So there may be many unnecessary overhead between IIS server and db server.
So, is there a better way to do this? Is there something equivalent to System.Linq.Expressions in linq to sql?
Make use of Dynamiclinqlibrary or Predicatebuilder will resolve problem you are facing
Find example for both approch : Dynamic query with Linq
Other problem with you code is you used IEnumerable , insted of it use IQuerable when you are getting data from the datasources like database, xmlfile etc.
The major difference is that IEnumerable will enumerate all elements, while IQueryable will enumerate elements, or even do other things, based on a query. In case of IQueryable Linq Query get used by IQueryProvider which must interpret or compiled in order to get the result.
Read with Example : IQueryable Vs. IEnumerable in terms of LINQ to SQL queries
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.