开发者

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

it seems the old indexes are retained when moving i开发者_运维技巧tems 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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜