C# LINQ orderby
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:
var calculation = from y in x.Elements("row")
orderby (int) y.Element("BUILD_ORDER")
select new
{
calcAttribute = y.Element("ELEMENT").Value
};
Is there any reason why you're using an anonymous type though, rather than just selecting the value you want? For example:
var calculation = from y in x.Elements("row")
orderby (int) y.Element("BUILD_ORDER")
select y.Element("ELEMENT").Value;
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 of int
for BUILD_ORDER
, and a conversion to string
for ELEMENT:
var calculation = from y in x.Elements("row")
orderby (int?) y.Element("BUILD_ORDER")
select (string) y.Element("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.
Looks good to me. You could also use Int32.Parse(...)
. I'm not aware of any built-in method for sorting strings as integers, but you certainly could write your own.
Yes, since your XML values are not typed, you have to cast them manually for .NET to be able to sort numerically.
By the way, int.Parse
will give you slightly better performance.
Looks like it's reading the build order as a string instead of an int. Your sample should work, or try
orderby int.Parse(y.Element("BUILD_ORDER").Value)
精彩评论