tags:

views:

157

answers:

3

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
+1  A: 

Use IList.Insert Method.

Ismail
+1  A: 

Lists grow dynamically to accommodate items as they are added. You would have to initialize the list with a predefined size. The easiest way I can think of to do that would be:

var myList = new Model[100].ToList();

That'll give you a list with 100 items, all null. You're then free to assign a value to myList[3].

Note that in your code you are trying to instantiate an IList<Model> which isn't possible - you need a concrete type (like List<Model>) rather than an interface.

Matt Hamilton
What I would like to do is stick a new item in position 3, but apparently lists need to be contiguous, so I need to create blank items at positions lower than 3 then insert a new item.
Dr. Zim
Ok, so my answer is one way to do that. Prepopulate the list with null items (up to the maximum amount you think you'll need) then assign just the ones you want.
Matt Hamilton
+1  A: 

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.

this. __curious_geek