通过两个属性ParentID和ChildID对列表进行排序 [英] Ordering a list by two properties, ParentID and ChildID

查看:276
本文介绍了通过两个属性ParentID和ChildID对列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有3个属性的类:名称,ID和ParentID.

I have a class that has 3 properties: Name, ID, and ParentID.

我的数据:

        Name       ID     ParentID
        Event A    1      1
        Event B    2      1
        Event C    3      1
        Event D    4      2

我在列表中包含了所有内容,并试图使用OrderBy或Sort方法.不知道哪个会更好.

I have everything in a List and was trying to use the OrderBy or perhaps the Sort methods. Not sure which would be better.

我需要对列表中的数据进行排序,以便事件将其子级作为列表中的下一个项目.对此的任何帮助将不胜感激,顺便说一句,我正在VB中进行此操作.谢谢!

I need the data in the list to be ordered so that an event has it's child as the next item in the list. Any help on this would be greatly appreciated, I am doing this in VB by the way. Thanks!!

推荐答案

您可以对列表进行排序

list.Sort(Function(x, y) 2 * x.ParentID.CompareTo(y.ParentID) + _
                         x.ChildID.CompareTo(y.ChildID))

说明:我在这里使用lambda表达式.您可以将其视为函数的一种内联声明. CompareTo返回-10+1.负数表示x小于y0都相等,而+1表示x大于y.通过将第一个比较乘以2,其符号优先于第二个比较.如果第一个返回0,则第二个仅起作用.

Explanation: I am using a lambda expression here. You can think of it as a kind of inline declaration of a function. CompareTo returns either -1, 0 or +1. A negative number means x is less than y, 0 both are equal and +1 means x is greater than y. By multiplying the first comparison by two, its sign takes precedence over the second comparison. The second has only an effect, if the first one returns 0.

使用列表Sort方法优于LINQ的优点是列表是就地排序的.使用LINQ,您将不得不创建一个新列表.

The advantage of using the lists Sort method over LINQ is that the list is sorted in-place. With LINQ you would have to create a new list.

这篇关于通过两个属性ParentID和ChildID对列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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