I have an Xelement containing a number of elements.
I have the following code to sort them:
var calculation = from y in x.Elements("row")
orderby y.Element("BUILD_ORDER").Value
select new
{
calcAttribute = y.Element("ELEMENT").Value
};
Which works fine, until BUILD_ORDER > 10, it orders 10 just after 1.
If I want it in strict numerical order, I case the element to an Int, is this the correct way to do it, or does LINQ have an inbuilt extension/method?
orderby Convert.ToInt32(y.Element("BUILD_ORDER").Value)
LINQ to Objects doesn’t have the built in conversion, but LINQ to XML does:
Is there any reason why you’re using an anonymous type though, rather than just selecting the value you want? For example:
Note that both of these will throw an exception if the BUILD_ORDER or ELEMENT subelements are missing. You can fix that using a conversion to
int?instead ofintforBUILD_ORDER, and a conversion tostringfor ELEMENT:This will still fail if BUILD_ORDER exists but can’t be parsed as an integer of course.
If your data should always have these elements, the first form is better, as it’ll detect any data errors earlier.