使用排序依据&LT项目排序数组;> [英] Sort array of items using OrderBy<>

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

问题描述

我有一个项目数组,我想整理自己的属性之一。
我可以访问使用的 item.Fields [字段名]的项目属性。值的属性返回为一个字符串,但我可以把它转换为一个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.

我在排序依据&LT一看;>,但我不知道如何使用它的想法。

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

推荐答案

需要明确的是,排序依据将不到位数组排序 - 它会返回一个新的序列这是一个整理的复制的数组中。如果可以的话,那么你要的的东西的,如:

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 - 你可以不投字符串整数,你要分析它们。如果这是你的意思,你可能想:

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.

这篇关于使用排序依据&LT项目排序数组;&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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