在列表中间插入内容的好方法是什么? [英] What's a good way to insert something in the middle of a list?

查看:71
本文介绍了在列表中间插入内容的好方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个简单的问题.假设我有一个大约20至50个条目的小清单.像这样:

This is probably a simple question. Let's say I have a small list with around 20-50 entries or so. Something like:

class Item
{
   int ItemNumber;
   int OrderNumber;
   string Name;
}

stored in something like
List<Item>

这存储在通用列表或数组中,其中OrderNumber从1,2,3,4,.... 50开始.为了使事情变得容易,让我们假设OrderNumber已经由QuickSort在List中的其他地方排序了(除非使事情变得更复杂).

This is stored either in a generic list or array in where the OrderNumber goes from 1, 2,3,4,....50. To makes things easier, let's assume that the OrderNumber has already be sorted in the List by QuickSort somewhere else (unless that makes things more complicated).

比方说,我想将Item.OrderNumber = 30移到Item.OrderNumber = 20或类似的位置.当我这样做时,现在需要移动高于20的所有内容,以使原来的20现在变成21,现在的21现在变成22,依此类推,直到我达到30.还需要以其他方式移动,当Item.OrderNumber = 30时被移到Item.OrderNumber = 34,并且所有内容都必须向下移动.

Let's say I want to move Item.OrderNumber = 30 into the spot taken by Item.OrderNumber = 20 or something like that. When I do that, everything above 20 now needs to be shifted so that the old 20 is now 21, 21 is now 22, etc until I makes it to 30. It also needs to go the other way so when Item.OrderNumber = 30 is moved to Item.OrderNumber = 34 and everything has to be shifted downwards.

我正在考虑将列表重新冒泡几次,但我希望有一种更好的方法来执行此操作.尽管列表很小,但是对于各种不同的事情,这需要做很多事情.

I'm thinking about bubbling the list a few times, but I'm hoping there's a better way to do this. Although the list size is small, this needs to done a lot for various different things.

只是让您知道.结果最终必须以某种类型的事务存储在数据库中.

Just to let you know. The results eventually have to be stored in a database, in some type of transaction.

推荐答案

是否必须为List<T>?如果不是,则可以考虑使用SortedList<TKey, TValue>SortedDictionary<TKey, TValue>.然后,您可以使用OrderNumber作为键,然后让集合完成工作.

Does it have to be a List<T>? If not, you might consider using a SortedList<TKey, TValue> or a SortedDictionary<TKey, TValue>. You could then use the OrderNumber as the key, and just let the collection do the work.

或者,对于List<T>,您可以将List<T>.BinarySearch与适当的IComparer<T>结合使用,并按订单号进行比较-您将拥有:

Alterantively, for List<T> you can use List<T>.BinarySearch with an appropriate IComparer<T> which compares by order number - you'd have:

int position = list.BinarySearch(newOrder, orderComparer);
list.Insert(position >= 0 ? position : ~position, newOrder);

您可以在整个代码中使用相同的IComparer<T>实例,因为它是无状态的.

You can use the same IComparer<T> instance throughout your code, as it would be stateless.

查看全文

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