I want to write an linq extension (or a custom dictionary, sorted list list or whatever solution is best) that will allow me to add a value to a collection with its key being the ‘next available’ one.
For example:
int CreatedKey = IncrementDictionary.AddNext(myCustomer);
If the currently existing keys are as follows:
1
2
8
4
3
Then it would add the myCustomer into the dictionary with a key of 5 and it would return that key.
What do you think?
You can use SortedList with Extension method for Adding to next automatically retrieved key.
Assuming Data structure be any object, with numeric key,
Following is ExtensionMethod for SortedList
It can be used like following
The output is
You can use Dictionary, or any other data structure. In that case Double loop will be required. In case of SortedList, one loop is saved while searching key. This loop is internally used by
SortedList.Addfunction using BinarySearch Algorithm.Binary search is faster than looping all elements (for larger size data).