Reputation: 9080
Building from this question: Trying to concatenate columns in LINQ
Now I want to sort:
var orderByIndexVal = Convert.ToInt32(Request["iSortCol_0"]);
var direction = Request["sSortDir_0"];
var gridInfo =
from leader in db.SchoolLdrAdminAccesses
join emp in db.Employees
on leader.ID equals emp.ID
select new List<string> { leader.ID, emp.FirstName + " " + emp.LastName };
return Json(new
{
sEcho = param.sEcho,
iTotalRecords = gridInfo.Count(),
iTotalDisplayRecords = gridInfo.Count(),
aaData = gridInfo.ToArray()
},
JsonRequestBehavior.AllowGet);
After reading this post: LINQ sorting anonymous types?
My issue is that I don't have anything named in my gridInfo
What I've tried so far:
if (direction == "asc")
{
gridInfo = gridInfo.OrderBy(gi => gi[orderByIndexVal]);
}
else
{
gridInfo = gridInfo.OrderByDescending(gi => gi[orderByIndexVal]);
}
But I'm getting the following error:
LINQ to Entities does not recognize the method 'System.String get_Item(Int32)' method, and this method cannot be translated into a store expression.
On the following block of code:
return Json(new
{
sEcho = param.sEcho,
iTotalRecords = gridInfo.Count(),
iTotalDisplayRecords = gridInfo.Count(),
aaData = gridInfo.ToArray()
},
JsonRequestBehavior.AllowGet);
Upvotes: 0
Views: 176
Reputation: 18359
You need to materialize the list, so the order by
doesn't happen in the DB, but in .NET, after the concatenation takes place.
var gridInfo = (from leader in db.SchoolLdrAdminAccesses
join emp in db.Employees
on leader.ID equals emp.ID
select new string[]{ leader.ID.ToString(),
emp.FirstName + " " + emp.LastName })
.ToList();
Also note that using an array instead of a list uses less memory. Hope that helps.
Upvotes: 3
Reputation: 793
I think this is the problem
new List<string> { leader.ID, emp.FirstName + " " + emp.LastName };
the anonymous type you are selecting is two columns { Int, String } not a simple List
Just Select new { leader.ID, emp.FirstName + " " + emp.LastName };
the Select statement will make it an IEnumerable automatically, so you don;t need the List<> part
I am assuming leader.ID is an Int here (which may be wrong)
Upvotes: 0