Order items not changed after moving objects inside list by remove and add

断了今生、忘了曾经 提交于 2019-12-16 18:03:28

问题


it seems the old indexes are retained when moving items in an collection, how can I enasure that the items will be iterated in the new order with the new index after an move?

First I move items in an ordinary List:

elements.Remove(src);
int index = elements.IndexOf(target);
elements.Insert(index,src);

and then run an foreach loop

foreach(Element _element in elements){ /* enter code here*/ } 

and it will retain the items with in order they were before relocation.


回答1:


I have tested your problem with this code and it writes to Console 0 1 2 3 5 6 4 7 8 9 as expected.

        List<string> elements = new List<string>();

        for (int i = 0; i < 10; i++)
        {
            elements.Add(i.ToString());
        }

        string src = "4";
        string target = "7";

        elements.Remove(src);

        int index = elements.IndexOf(target);
        elements.Insert(index, src);

        foreach (string e in elements)
        {
            Console.Write("{0} ", e);
        }

So, with your current code I don't see where the problem could be.



来源:https://stackoverflow.com/questions/6289464/order-items-not-changed-after-moving-objects-inside-list-by-remove-and-add

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!