Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In LINQ to Entities, How can you order like follows?

I have a queryable of entities with a "Code" field against them

1.1.1,
1.1.2,
1.1.3,
1.1.4,
...,
1.1.10,
1.1.11

Unfortunately, When I do an .OrderBy(x=> x.Code) on the query, it returns in the following order

1.1.1,
1.1.10,
1.1.11,
1.1.2,
1.1.3,
...

How can I make it that the object list is ordered by the code field, split by the "."s and as an integer between each part?

This is customer data, so I can't just put a "0" in front of the 1 number ones. Also it is any number of "."s in this Code field.

Let me know if you require further information.

like image 646
Scott Becker Avatar asked Dec 18 '22 01:12

Scott Becker


2 Answers

If you can make some assumption like every node can have max n letter. you can use this code.

.OrderBy(x => String.Concat( x.Code.Split('.')
                                   .Select(ss => ss.PadLeft(3, '0'))) )
like image 89
Serkan Arslan Avatar answered Dec 31 '22 13:12

Serkan Arslan


The Version class should be a good approach for that. Unfortunately Version.Parse fails at Linq2Entity so you have to fetch the data first from your sql-server and sort it afterwards.

var result = input.AsEnumerable<string>().OrderBy(x => Version.Parse(x.Code));
like image 44
fubo Avatar answered Dec 31 '22 13:12

fubo