所列出的< T>保证插入顺序? [英] Does List<T> guarantee insertion order?

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

问题描述

说我有3字符串列表(如1,2,3)。

然后我要重新排序他们把2位置1(如2,1,3)。

我用这code(设置indexToMoveTo 1):

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

这似乎工作,但我偶尔会得到奇怪的结果;有时候顺序不正确,或从列表中的项目越来越删除!

任何想法?并执行列表为了保证?

相关报道:

  

<一个href="http://stackoverflow.com/questions/453006/does-a-listt-guarantee-that-items-will-be-returned-in-the-order-they-were-added">Does一个List&LT; T&GT;该项目将返回的顺序添加?保证

解决方案

名单,其中;&GT; 类不保证排序 - 事情会被保留在列表中的顺序你添加它们,包括重复,除非你明确地对列表进行排序。

您可能会得到您的code奇怪的结果,如果你移动的项目后,在列表中,为你的删除()将移动所有的其他项下调用之前一个地方插入()

您可以熬你的code下来的东西足够小后?

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

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

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!

Any ideas? and does List guarantee order?

Related:

Does a List<T> guarantee that items will be returned in the order they were added?

解决方案

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.

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?

这篇关于所列出的&LT; T&GT;保证插入顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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