如何使用重复键对列表进行排序? [英] How to sort the list with duplicate keys?

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

问题描述

我有一组元素/键,我正在从两个不同的配置文件中读取它们.因此,键可能相同,但与每个键关联的值不同.

I have a set of elements/keys which I'm reading from two different config files. So the keys may be same but with different values associated with each of them.

我想按排序顺序列出它们.我能做什么 ?我尝试使用 SortedList 类,但它不允许重复键.

I want to list them in the sorted order. What can I do ? I tried with SortedList class but it does not allow duplicate keys.

我该怎么做?

例如,假设我有 3 个元素,键为 1,2,3.然后我又得到一个具有键 2(但值不同)的元素.然后我希望在现有键 2 之后但在 3 之前插入新键.如果我再次找到带有键 2 的元素,那么它应该在最近添加的键 2 之后插入.

e.g Lets say I have 3 elements with keys 1,2,3. Then i get one more element having key 2 (but different value). Then I want the new key to get inserted after existing key 2 but before 3. If I againg find an element with key 2, then it should go after most recently added key 2.

请注意,我使用的是 .NET 2.0

Please note than I'm using .NET 2.0

推荐答案

我更喜欢将 LINQ 用于这种类型的事情:

I prefer to use LINQ for this type of thing:

using System.Linq;

...

var mySortedList = myList.Orderby(l => l.Key)
                         .ThenBy(l => l.Value);

foreach (var sortedItem in mySortedList) {
    //You'd see each item in the order you specified in the loop here.
}

注意:您必须使用 .NET 3.5 或更高版本才能完成此操作.

Note: you must be using .NET 3.5 or later to accomplish this.

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

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