Linq – How to use the System.LINQ.Dynamic assembly w/ IEnumerable(Of T)

dynamiclinqsorting

I'm trying to take the final solution from Phil Haack here and sort using his killer LINQ query but instead of using data context like he is, I want to query against IEnumerable(Of T) … not having any luck.

Public Function DynamicGridData(ByVal sidx As String, ByVal sord As String, ByVal page As Integer, ByVal rows As Integer) As ActionResult
Dim list As List(Of User) = UserService.GetUserCollection()
Dim FilteredAndSortedList = list.OrderBy(sidx + " " + sord).Skip(pageIndex * pageSize).Take(pageSize)

Return JSON(jsonData)
End Function

Currently I get the error below my .OrderBy(sidx + " " + sord) line

"Data type(s) of teh type parameter(s) in extension method 'Public Function OrderBy(Of TKey)(keySelector As System.Func(Of User, TKey)) As System.Linq.IOrderedEnumerable(Of User)' defined in 'System.Linq.Enumerable' cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error."

EDIT:

I found the issue to be that my "list" in the example above was not of type IQueryable. Simply adding .AsQueryable() did the trick!

Public Function DynamicGridData(ByVal sidx As String, ByVal sord As String, ByVal page As Integer, ByVal rows As Integer) As ActionResult
Dim list As List(Of User) = UserService.GetUserCollection()
Dim FilteredAndSortedList = list.AsQueryable().OrderBy(sidx + " " + sord).Skip(pageIndex * pageSize).Take(pageSize)

Return JSON(jsonData)
End Function

Best Solution

I'm not positive but I think it has to do with the fact that your passing into OrderBy a string as opposed to an Expression(TDelegate) which is what it expects.

Take a look at this article and see if it helps.

http://msdn.microsoft.com/en-us/library/bb549264.aspx

Edit:

I've taken a look at Phil's Code and at some further documentation provided by Scott Gu. You should be able to pass in a string in which to order by. That being the case my next question would be if you take out the order by does your app work? The reason for this is I'm wondering if we have another underlying error that we are missing. Like for instance you are returning JSON(jsondata) but I dont see where you are initializing jsondata. Now I dont think that is your error cause you state you are getting it on the orderby statement. However if you are actually getting the error because the object you are trying to order is empty then you have another underlying issue.