是否列出<T>保证广告订单? [英] Does List&lt;T&gt; guarantee insertion order?

查看:20
本文介绍了是否列出<T>保证广告订单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在一个列表中有 3 个字符串(例如1"、2"、3").

Say I have 3 strings in a List (e.g. "1","2","3").

然后我想重新排列它们以放置2"位置 1(例如2"、1"、3").

Then I want to reorder them to place "2" in position 1 (e.g. "2","1","3").

我正在使用此代码(将 indexToMoveTo 设置为 1):

I am using this code (setting indexToMoveTo to 1):

listInstance.Remove(itemToMove);
listInstance.Insert(indexToMoveTo, itemToMove);

这似乎有效,但我偶尔会得到奇怪的结果;有时订单不正确或列表中的项目被删除!

This seems to work, but I am occasionally getting strange results; sometimes the order is incorrect or items from the list are getting deleted!

有什么想法吗?List 是否保证顺序?

Any ideas? Does List<T> guarantee order?

做一个列表保证商品会按照添加的顺序退回?

推荐答案

List<> 类确实保证排序 - 除非您明确对列表进行排序,否则内容将按照您添加它们的顺序保留在列表中,包括重复项.

The List<> class does guarantee ordering - things will be retained in the list in the order you add them, including duplicates, unless you explicitly sort the list.

根据 MSDN:

...List "表示一个强类型的对象列表,这些对象可以按索引访问."

...List "Represents a strongly typed list of objects that can be accessed by index."

索引值必须保持可靠才能准确.因此订单是有保证的.

The index values must remain reliable for this to be accurate. Therefore the order is guaranteed.

如果您在列表的后面移动项目,您的代码可能会得到奇怪的结果,因为您的 Remove() 将在调用 Insert().

You might be getting odd results from your code if you're moving the item later in the list, as your Remove() will move all of the other items down one place before the call to Insert().

你能把你的代码简化成足够小的东西来发布吗?

Can you boil your code down to something small enough to post?

这篇关于是否列出<T>保证广告订单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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