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