tags:

views:

152

answers:

1

This is a very short question and I fear the answer is short too.

Is there any way of doing anything along the lines of

Func<DataContext, string, bool, IEnumerable<X> fnMyQuery = CompiledQuery.Compile<DataContext, string, bool IList<X>(
     (db, sortColumn, sortDesc) => (
          (!sortDesc)?
              db.OrderBy(x => DynamicResolve(sortColumn))
          :
              db.OrderByDescending(x => DynamicReolve(sortColumn))
      ));

Said in another way, I'd like to create a compiled query that can take in a column and a sort order and then sort my results in the so desired way - I can work out how to do this without having the query compiled - but is it possible with a compiled query using LINQ to SQL?

A: 

The point of CompiledQuery.Compile is to produce a fully translated and ready to go method which evaluates the query.

Fully translated.

Of course, there's nothing stopping you from doing the sort outside of the database (source might be a compiled query).

public IList<T> SortedResults<T>(IEnumerable<T> source,
  string sortColumn, bool sortDesc)
{
  List<T> results = source.ToList();
  if (!sortDesc)
  {
    results = Enumerable
      .OrderBy(results, x => DynamicResolve(sortColumn))
      .ToList();
  }
  else
  {
    results = Enumerable
      .OrderByDescending(results, x => DynamicResolve(sortColumn))
      .ToList();
  }
  return results;

}
David B
I know this, and obviously there's no issue in, say sorting 10 items, but when trying to page, this becomes and issue, if you're paging over tons of records sorted by a column - sorting on the client side then becomes a problem seeing as the slicing is done there too. However thank you for the idea, but I suspect the way to really read your answer is a simple "no, this is not possible".
kastermester
If you're paging, you shouldn't ToList after sorting... you should Skip and Take.
David B
The Issue I'm talking of this is, consider a collection of, let's say 1.000.000 items. And you do var list = myCollection.OrderBy(s => s.Title).Skip(5000).Take(10).ToList(); With the approach you suggest I'd have to take out the entire collection of the database, then sort it, and now skip and take (ie, this will be slow!). The idea for me of using a compiledquery is to be faster - not slower.
kastermester
You have ToList in your example code in the question. All 1 M items would be ordered and returned by the database if you ran that.
David B
Woops - that's a mistake, the idea here is to compile a query to avoid redundant expression tree parsing, but still get all the heavy-lifting done by the database - thanks for picking that up - I will change it to reflect the changes.
kastermester