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

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

问题描述

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

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

然后我想重新排序, 2,例如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!

任何想法? 列表< T> 保证令?


列表< T>保证项目将按照添加的顺序返回?


推荐答案

列表<> 类确保订购 - 除非您明确地对列表进行排序,否则会按照添加顺序保留在列表中,包括重复。

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.

如果您稍后在列表中移动该项,您的代码可能会得到奇怪的结果,因为您的 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?

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

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