Search code examples
c#linqlinq-to-entitiessql-order-by

How to OrderBy an integer in a string field in a Linq query


I have some data coming out of an DB that I can't readily change the schema of. I want to sort it and bind it to a control based on a numerical ID. The problem is that the API stores the number in a string field instead of as an int and Linq barfs on the conversion attempt.

myControl.DataSource = dataFromDB.OrderBy(o => int.Parse(o.StringHoldingAnInt));

LINQ to Entities does not recognize the method 'Int32 Parse(System.String)' method, and this method cannot be translated into a store expression.

Convert.ToInt32 doesn't work either.

LINQ to Entities does not recognize the method 'Int32 ToInt32(System.String)' method, and this method cannot be translated into a store expression.

Sorting as a string isn't suitable because the values aren't all the same length and it would order them like this: 1, 10, 11, 2, 3..


Solution

  • This won't be nearly as efficient because you're not harnessing the database query to filter your results, but this would basically query for all data, then filter on the client.

    myControl.DataSource = dataFromDB.ToList().OrderBy(o => int.Parse(o.StringHoldingAnInt));