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..
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.
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.
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.
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));
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With