开发者

Adding items to the beginning of a list array

开发者 https://www.devze.com 2023-04-12 00:27 出处:网络
I am currently working on a C# project where I have a list initialised with a class object, i.e. List<MyClass> myList = new List<MyCl开发者_如何转开发ass>();

I am currently working on a C# project where I have a list initialised with a class object, i.e. List<MyClass> myList = new List<MyCl开发者_如何转开发ass>();

I have added some data to this list, but I need to add more data to it, however, it needs to to the beginning of the array, not at the end, is there a way that I can do this.

Thanks for any help you can provide.


Depends on the type your "MyList" is of! If it's a simple List, then

myList.Insert(0, new MyClass());

will solve your problem!


I am assuming that you are using List and for that you can make use of

List<string> mylist = new List<string>();
string[] input = { "fist", "second"  }
mylist.InsertRange(0, input);

more : List.InsertRange Method


First of all, what you are describing is not an Array but a List. An array will be:

var myArray = new MyClass[]{new MyClass("foo"), new MyClass("Bar"};

Secondly, arrays implement IList of T and ICollection of T but the methods are implemented explicitly (you have to cast) and the Add/Insert/Remove throw not implemented Exception. This means that the System.Array class is kind of immutable.

Last, as other has mentioned here if you are using a List you can call the Insert. Which has two parameters, the first one is the index where you want to insert the item and the second one is the element to insert:

myList.Insert(0, new MyClass("aaa"))


EDIT: Question changed to clarify that List<T> is being used

You can use Insert() to add at a specific index (use 0 for the beginning). Here is the documentation for List<T>.Insert()

http://msdn.microsoft.com/en-us/library/sey5k5z4.aspx


If you are only ever adding to the front of the list it might be worth wrapping a standard list so that internally it adds them to the end but when you iterate over it it runs in reverse.

This is because Insert is O(n) and Add is O(1) provided the list doesn't have to resize internally.

0

精彩评论

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