views:

404

answers:

2

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

A: 

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');
Mitch Wheat
I thought of something like this too, but how could I apply this to the sort predicate shown above? I would need to pad the .Value for the predicate, and I cannot figure out how that syntax would work.
Ash Machine
OK, now I get it:Func<MyObject, string> sortClause = p => p.MyObjectProperties.Find(s => s.Name == theSortProperty).Value.ToString().PadLeft(8, '0');thanks!
Ash Machine
A: 

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.