Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding an IList item to a particular index number

Tags:

c#

ilist

Our Client's database returns a set of prices in an array, but they sometimes don't include all prices, i.e., they have missing elements in their array. We return what we find as an IList, which works great when we retrieve content from the database. However, we are having difficulties setting the elements in the proper position in the array.

Is it possible to create an IList then add an element at a particular position in the IList?

var myList = new List<Model>();
var myModel = new Model();
myList[3] = myModel;  // Something like what we would want to do
like image 253
Zachary Scott Avatar asked Jun 01 '10 04:06

Zachary Scott


1 Answers

Use IList<T>.Insert(int index,T item)

IList<string> mylist = new List<string>(15); 
mylist.Insert(0, "hello");
mylist.Insert(1, "world");
mylist.Insert(15, "batman"); // This will throw an exception.

From MSDN

If index equals the number of items in the IList, then item is appended to the list.

In collections of contiguous elements, such as lists, the elements that follow the insertion point move down to accommodate the new element. If the collection is indexed, the indexes of the elements that are moved are also updated. This behavior does not apply to collections where elements are conceptually grouped into buckets, such as a hash table.

like image 98
this. __curious_geek Avatar answered Oct 13 '22 19:10

this. __curious_geek