使用 OrderBy<> 对项目数组进行排序 [英] Sort array of items using OrderBy&lt;&gt;

查看:21
本文介绍了使用 OrderBy<> 对项目数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组项目,我想对它们的一个属性进行排序.我可以使用 "item.Fields["FieldName"].Value" 访问 items 属性,该属性作为字符串返回,但我可以将其转换为 int.

I have an array of items and I would like to sort on one of their properties. I can access the items property using "item.Fields["FieldName"].Value" the property is returned as a string but I can cast it to an int.

我看过 OrderBy<> 但我不知道如何使用它.

I had a look at OrderBy<> but I have no idea of how to use it.

推荐答案

需要明确的是,OrderBy 不会对数组进行原地排序 - 它会返回一个新的序列,它是一个已排序的 复制数组.如果没问题,那么你想要东西,比如:

To be clear, OrderBy won't sort the array in place - it will return a new sequence which is a sorted copy of the array. If that's okay, then you want something like:

var sorted = array.OrderBy(item => item.Fields["FieldName"].Value);

另一方面,我不明白您的评论,即该属性作为字符串返回,但您可以将其转换为 int - 您不能将字符串转换为 int,您必须解析它们.如果这就是您的意思,您可能想要:

On the other hand, I don't understand your comment that the property is returned as a string but that you can cast it to an int - you can't cast strings to ints, you have to parse them. If that's what you meant, you probably want:

var sorted = array.OrderBy(item => int.Parse(item.Fields["FieldName"].Value));

如果你想把它作为一个数组,你可以在之后调用 ToArray():

If you want that as an array, you can call ToArray() afterwards:

var sorted = array.OrderBy(item => int.Parse(item.Fields["FieldName"].Value))
                  .ToArray();

或者,如果您想就地排序,您可以使用 Array.Sort,但这会有些混乱.

Alternatively you could use Array.Sort if you want to sort in-place, but that will be somewhat messier.

这篇关于使用 OrderBy<> 对项目数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆