简体   繁体   中英

Sorting MultiValue data numerically OR alphabetically - LINQ to SQL and C#3

I am having a problem giving a LINQ predicate the knowledge it needs to sort either alphabetically or numerically.

I am working with a multi-value pivoted set of data with has a sortable column. The column is always stored as varchar in the DB, however, it has lookup knowledge of what that data type actually is. To simplify, in addition to strings the column can contain integers.

I have written a general-purpose (and working) sorting predicate as follows.

Func<MyObject, string> sortClause = p => p.MyObjectProperties.Find(s => s.Name == theSortProperty).Value;

The problem is that if my sortable column contains numerical values (stored as varchar in the DB), I get

13
131   <-- 131 between 13 and 14!!!
14
15 

Of course, alphanumerically this is correct.

As I said, I know programmatically the type of data (string or integer) for theSortProperty. I want to be able to instruct the predicate to sort using alphabetical means OR numerical means. I see no easy way to accomplish this, since my LINQ to SQL mapping declares that column as [Column(Storage="_Value", DbType="NVarChar(MAX)", UpdateCheck=UpdateCheck.Never)]

Yet I am sure someone must have seen this before and can offer a suggestion. I should mention that NHibernate or other ORMs are out of the question for me.....Thanks

One way to achieve this is to pad your string numerical values with zeros, up to the length of the widest value that can occur, and sort on the padded value:

string s = "131";
s =  s.PadLeft(8, '0');

You can use some of the the System.Convert functions in your LINQ query. If you change your orderby to System.Convert.ToInt32(), you should be able to sort numerically rather than lexicographically.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM