使用Linq对列表中的列表进行排序 [英] Using Linq to order lists within a list

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

问题描述

你好,

我有一个项目列表(实际上是IEnumerable).每个项目都有一个值列表.例如:

Item1.Value [0] ="健康&安全"
Item1.Value [1] =经济"
Item1.Value [2] =环境"

Item2.Value [0] =信誉"
Item2.Value [1] =环境"
Item2.Value [2] =法规"

...

如何使用linq排序值列表?我知道我可以使用以下命令订购商品列表:

Items.Orderby(x => x.something)

...但是如何获取每个项目中的值列表?

Hello,

I have a list of items (actually an IEnumerable). Each item has a list of values. For example:

Item1.Value[0] = "Health & Safety"
Item1.Value[1] = "Economic"
Item1.Value[2] = "Environment"

Item2.Value[0] = "Reputation"
Item2.Value[1] = "Environment"
Item2.Value[2] = "Regulatory"

...

How can I order the list of values using linq? I know I can order the list of items using something like:

Items.Orderby(x => x.something)

...but how do I get to the list of values in each item?

推荐答案

取决于值的定义方式以及是否要持久化或不是.如果您只是对Value的排序项进行什么操作,但又不想真正更改其顺序,则可以对Value数组/列表使用OrderBy.

Depends on how Value is defined and whether you want it persisted or not. If you simply what the sorted items of Value but don't want to actually change their order then you can use OrderBy on the Value array/list.

var sortedValues = Item1.Value.OrderBy(v => v);

如果要更新值"以具有排序后的值,则需要用新值替换现有值".这意味着该属性必须是可写的.如果它不可写,那么您将无法保留排序后的顺序.如果可写,则 上面的代码应该可以工作.

If you want Value to be updated to have the sorted values then you'll need to replace the existing Value with the new one. That means the property has to be writable. If it isn't writable then you cannot persist the sorted order. If it is writable then the aforementioned code should work.

Item1.Value = Item1.Value.OrderBy(v => v);

如果Value是一个数组,则可以使用 Array.Sort 对数组进行排序.

If Value is an array then you can use Array.Sort to sort the array in place.

迈克尔·泰勒
http://www.michaeltaylorp3.net

Michael Taylor
http://www.michaeltaylorp3.net


这篇关于使用Linq对列表中的列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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