Either I'm missing something very obvious here or it IS the problem.
Insert method of List<> adds another item on specified index but not overriding it.
actionsIds.Insert(0, "item1");
actionsIds.Insert(1, "item2");
actionsIds.Insert(0, "item3");
MessageBox.Show(actionsIds.Count.ToString());
I'm getting count = 3..Why is it not overriding it or is it actually not for this purpose?
Insert
(https://msdn.microsoft.com/en-us/library/sey5k5z4(v=vs.110).aspx) adds a new item at the specified index, if you need to replace an item at a specific index then you should use the indexer property (https://msdn.microsoft.com/en-us/library/0ebtbkkc(v=vs.110).aspx).
actionsIds[0] = "item1";
When doing it this way, you need to make sure that the index exists otherwise it will cause an exception. You can do so by checking Count
if you are unsure if the index in question exists or not.
if (index >= 0 && index < actionsIds.Count)
actionsIds[index] = item;
You can add an else
block to the above if you want to insert to the list if the index doesn't exist (using Add
or Insert
)
The List<>.Insert is used to add an item into the list at the given position. So basicly it pushes all item 1 "index" further in order to create a spot for the item you wanted
your exemple did the folowing:
Step 1: item1
Step 2: item1 - item2
Step 3: item3 - item1 - item2
If your goal is to replace at a given position I would suggest you to RemoveAt(Index) then Insert or to use this:
yourList[index] = "item2";
Edit:
If the item is going to be added for the first time it then means you are at the end of the list. That being said, this piece of code would do the job.
if(index <= yourList.Count)
{
yourList[index] = "item2";
}
else
{
//You can chose one of these
yourList.Add("item2"); //1
yourList.Insert(index,"item2"); //2
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With