views:

51

answers:

2

This question (LINQ and a natural sort order…) talks about how to implement natural sorting in Linq using an IComparer. I've used this successfully in the past with IEnumerables, but I am unable to make it work in Linq-to-SQL expressions. Is this because the specific overload of .OrderBy() that takes an IComparer is not supported by Linq-to-SQL?

If this is in fact the case, are there any practical workarounds?

+1  A: 

Yes. Linq-to-SQL translates your lambda expressions directly into sql, so it obviously cannot handle arbitrary code. You could use ToList() to force query execution, and then perform your OrderBy on that list.

Gabe Moothart
Thanks, that's was the answer I was pretty confident I'd get. A guy can always hope, though.
James Sulak
+1  A: 

It's not that the IComparer is not supported, it is that in Linq-to-Sql, an OrderBy() must be translated to a T-Sql operation. If it allows you to specify criteria for comparisons, The C# code behind it would have to be executed by SQL server to use it.

If you need to do something in Linq-To-Sql that is not supported but which can be done in T-SQL, you can always get around it by using a stored procedure, which work splendidly with Linq-to-Sql. If that it inconvenient, you can call the ToList() method to invoke the execution and then sort it in memory. The practicality of this depends on the size of the data and how much of it you wished to fetch (such as when implementing pagination).

Phil Gilmore