Search code examples
c#sql-serverwinformssql-server-ce

How to sort nvarchar column in C#


I am facing problem in sorting the column with nvarchar datatype. How do i sort this in ascending order. Data is in this format...

1/0
22/21
19/26
2.3/14
29/0
1.3/44
85/30

First values is kilometer, either it can be integer or double then a forward slash and the last value is pole number, it will be integer always.

this data is generated by concatenating two columns, i.e

select fromkm+"/"+frompole as FROM_KM from station;

fromkm and frompole are nvarchar type in database

Result should be in the following formate

1/0
1.3/44
2.3/14
19/26
22/21
29/0
85/30

Thanks


Solution

  • Do the sort in SQL using order by. Note that since your data is stored as nvarchar you'll have to cast it to float / int when sorting (or better yet - change the data types of the columns in the database):

    select fromkm +"/"+ frompole as FROM_KM 
    from station
    order by cast(fromkm as float), cast(frompole as int);