Other collection type
Or is there any other better collection?
You could use a Dictionary. Usage example:
using System.Collections.Generic;
...
var items = new Dictionary<int, int>();
items.Add(3, 1000); // will throw error if 3 already exists
// Or update
items[3] = 1000: // will not throw error if already exists or doesn't exist!
Please note that the order of the dictionary is not guaranteed. From the docs
The order in which the items are returned is undefined.
If you need a guarantee of the ordering, you could use a SortedList or a
SortedDictionary.
using System.Collections.Generic;
...
var items = new SortedList<int, int>();
items.Add(3, 1000); // will throw error if 3 already exists
// Or update
items[3] = 1000: // will not throw error if already exists or doesn't exist!
using System.Collections.Generic;
...
var items = new SortedDictionary<int, int>();
items.Add(3, 1000); // will throw error if 3 already exists
// Or update
items[3] = 1000: // will not throw error if already exists or doesn't exist!
The difference between SortedList and SortedDictionary is performance. Quote from the docs:
Where the two classes differ is in memory use and speed of insertion and removal
The (Sorted)Dictionary and SortedList works a bit different compared to lists and arrays. I would recommend to read the linked Microsoft documentation when using one of them.
null
values in a list or array
I will have to pad the first and the second elements with null for me to able to insert something at the 3rd index
Please note that you cannot add null
values in a list or array of ints. That would be only possible with "nullable ints". (so new List<int?>()
)