Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to OrderBy an integer in a string field in a Linq query [duplicate]

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..

like image 492
Dan Is Fiddling By Firelight Avatar asked Nov 10 '11 20:11

Dan Is Fiddling By Firelight


People also ask

Does OrderBy work on string?

OrderBy" function utilizes the default comparer for a string. That comparer is not necessarily going to return a sort order based on the ASCII code. For a list of all the different string comparers, see the article on MSDN.

Can you use LINQ on a string?

LINQ can be used to query and transform strings and collections of strings. It can be especially useful with semi-structured data in text files. LINQ queries can be combined with traditional string functions and regular expressions. For example, you can use the String.

What is difference between OrderBy and ThenBy in LINQ?

Generally, ThenBy method is used with the OrderBy method. The OrderBy() Method, first sort the elements of the sequence or collection in ascending order after that ThenBy() method is used to again sort the result of OrderBy() method in ascending order.


2 Answers

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)); 
like image 73
Steve Danner Avatar answered Oct 12 '22 07:10

Steve Danner


Came up with a simple trick to fix this: First order by length and then normaly.

dataFromDB.OrderBy(o => o.StringHoldingAnInt.Length).ThenBy(o => o.StringHoldingAnInt) 

This is all done in DB and doesn't load into memory.

like image 30
Pops Avatar answered Oct 12 '22 07:10

Pops