OrElse
OrElse

Reputation: 9959

LINQ: Sort by (Treat letters as numbers)

How should i use linq to sort my data when my data contain both numbers and letters?

For example my current linq

Dim MyQuery = From c In XDoc.Descendants() _
Where c.Attribute(Y) IsNot Nothing And c.Attribute(Str) IsNot Nothing _
Order By Val(c.Attribute(Y).Value), Val(c.Attribute(X).Value) _
Select Str = c.Attribute(Str)

returns something like the following

13
167   
172   
231      
44    
49  

which is not what i would like it to be... The output should be like the one below

13
44    
49 
167   
172   
231      

Any ideas? Thank you for your time

Upvotes: 2

Views: 690

Answers (2)

Adam Ralph
Adam Ralph

Reputation: 29956

Convert the strings to numbers in your sort clause, e.g.

Dim MyQuery = From c In XDoc.Descendants() _
Where c.Attribute(Y) IsNot Nothing And c.Attribute(Str) IsNot Nothing _
Order By CInt(c.Attribute(Y)), CInt(c.Attribute(X)) _
Select Str = c.Attribute(Str)

Note that if any of the strings cannot be converted to an int (or whatever numeric type you decide you need to use) then you will get an exception. In this case, you will have to do something a little more involved, such as projecting your sequence onto a new sequence with any strings representing numerics converted to numerics and the rest left as they are, the result being alphanumeric sorting.

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1499770

Don't use the Value property of XAttribute - use the explicit conversion to Integer. I think this should do it:

Dim MyQuery = From c In XDoc.Descendants() _
Where c.Attribute(Y) IsNot Nothing And c.Attribute(Str) IsNot Nothing _
Order By CInt(c.Attribute(Y)), CInt(c.Attribute(X)) _
Select Str = c.Attribute(Str)

Note that it's generally a better idea to use the explicit conversions supported by XAttribute and XElement than to use Int32.Parse etc, as then the XML-specific parsing will be performed, following the appropriate standard formats.

Upvotes: 3

Related Questions