C# LINQ 排序
我有一个包含多个元素的 Xelement。
我有以下代码对它们进行排序:
var calculation = from y in x.Elements("row")
orderby y.Element("BUILD_ORDER").Value
select new
{
calcAttribute = y.Element("ELEMENT").Value
};
效果很好,直到 BUILD_ORDER > 10,它在 1 之后排序 10。
如果我想要严格的数字顺序,我将元素设置为 Int,这是正确的方法吗,还是 LINQ 有内置扩展/方法?
orderby Convert.ToInt32(y.Element("BUILD_ORDER").Value)
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
LINQ to Objects 没有内置转换,但 LINQ to XML 具有:
是否有任何理由使用匿名类型,而不仅仅是选择所需的值?例如:
请注意,如果缺少 BUILD_ORDER 或 ELEMENT 子元素,这两者都会引发异常。您可以使用将
BUILD_ORDER
转换为int?
而不是int
的转换,以及将string
转换为string
来解决此问题ELEMENT:如果 BUILD_ORDER 存在但不能被解析为整数,这仍然会失败。
如果您的数据应该始终包含这些元素,则第一种形式更好,因为它会更早地检测到任何数据错误。
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 ofint
forBUILD_ORDER
, and a conversion tostring
for 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.
我觉得不错。您还可以使用
Int32.Parse(...)
。我不知道有任何内置方法可以将字符串作为整数进行排序,但您当然可以编写自己的方法。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.是的,由于您的 XML 值不是类型化的,因此您必须手动转换它们以使 .NET 能够按数字排序。
顺便说一下,
int.Parse
会给你带来稍微更好的性能。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