Convert string to int for ordering using LINQ

Dave Mateer picture Dave Mateer · May 12, 2011 · Viewed 17.7k times · Source

I'd like to order my list by a string converted into an int:

var orderedListOfRfidTags = uow.RfidTags.OrderBy(t => Convert.ToInt32(t.Number)).ToList();

but get: The method 'ToInt32' is not supported.

Answer

Ahmed Magdy picture Ahmed Magdy · May 13, 2011

What about:

var orderedListOfRfidTags = uow.RfidTags.OrderBy(t => t.Number).ToList();

remove any CLR method so ORM can transform it to a known SQL query

EDIT: I just read want to convert it first so:

var orderedListOfRfidTags = uow.RfidTags.ToList().OrderBy(t => Convert.ToInt32(t.Number));

either to get all from DB then order it on the client (linq to object) as I mentioned before or find a method on your ORM to cast to int the order it. Before you order Select a new list with a Number converted then order by it.

Edit2:

What about the direct cast is it working with this ORM?

var orderedListOfRfidTags = uow.RfidTags.OrderBy(t => (int)t.Number).ToList();