Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# List - Add to the bottom of the list

Tags:

c#

list

I have a List<T> and want to start adding from the bottom but I'm getting a runtime IndexOutOfBoundsException.

I have initialized a list with a capacity:

List<ClassA> ClassesOfA = new List<ClassA>(10);
...
...
ClassesOfA[5] = classAObj;
...

Is there anyway to do this?

I need to do this because I'm analyzing another list from the bottom and adding the result to this list. So I need to be able to add from the bottom. Is there any way to do this rather than initializing the List<ClassA> with ClassA objects before adding my objects?

like image 405
madu Avatar asked Dec 08 '22 16:12

madu


2 Answers

To add items to the list, you should be calling ClassesOfA.Add(). Any items added this way will be added to the end of the list (not sure if the beginning of the list or the end of the list is what you consider the bottom).

like image 103
Justin Niessner Avatar answered Dec 11 '22 10:12

Justin Niessner


You can try adding the elements like this: ClassesOfA.Add(classAObj), then when all the list elements are added you can call ClassesOfA.Reverse() to reverse the order of the objects inside the list.

like image 29
marosoaie Avatar answered Dec 11 '22 09:12

marosoaie