1

I'm trying to Insert an item at the start of a list using foo.Insert(0, bar); but it seems that the item that was at index 0 before is getting bumped to the back of the list instead of moving to index 1. I've tried creating a new List and adding the values in order, but it looks messy/hacky.

Is there any clean way of doing this? If so, how?

Thank you.

Maksim Simkin
  • 9,561
  • 4
  • 36
  • 49
  • 4
    you are doing something wrong, insert just shifts all items that a behind inserting position, so that previuos 0 item should get index 1 – Maksim Simkin Jan 02 '17 at 14:07
  • 1
    If you care about order, perhaps you should use [`Stack`](https://msdn.microsoft.com/en-us/library/system.collections.stack(v=vs.110).aspx) instead. – Bart Friederichs Jan 02 '17 at 14:08
  • 1
    Can you provide a [Minimal, Complete And Verifiable Example](http://stackoverflow.com/help/mcve)? I cannot reproduce that. If I insert at index 0, all other elements get simply shifted up. Nothing is moved to the end of the list. – René Vogt Jan 02 '17 at 14:08
  • Yes, use other type of collection. For example stack – Renatas M. Jan 02 '17 at 14:08
  • Please provide some code since insert is shifting all elements >= index one index higher. – Trickzter Jan 02 '17 at 14:09
  • 1
    List does preserve ordering - so not sure what's going on here, maybe http://stackoverflow.com/questions/1043039/does-listt-guarantee-insertion-order will help? – C. Knight Jan 02 '17 at 14:13

1 Answers1

3

As already said in comments, insert into List<T> preserve ordering, so described behaviour shouldn't happen.

Simple example:

var lst = new List<int> {1,2,3,4};
lst.Insert(0,0);
lst.Dump();

enter image description here

Maksim Simkin
  • 9,561
  • 4
  • 36
  • 49
  • 1
    The source code guarantees it: https://referencesource.microsoft.com/#mscorlib/system/collections/generic/list.cs,49c519bce0cdbd82 line 677 – C. Knight Jan 02 '17 at 14:19