I would like to get the same behavior as of List.Insert(Index, content ) In List , it just pushes the rest of elements forward while enables you to insert new element at specified index.
But I am dealing Concurrency so I can't use List anymore instead I need to use Concurrent collection. Any idea how we can achieve this?
Note :
I am trying to achieve custom Sorting of custom Objects stored in the concurrent collection( i.e. If at index = 2, Last Name is alphabetically less than the incoming LastName, it must allow the incoming to be placed at index = 2 , while pushing /sliding the old value to next indexes. Thus retaining all contents with new one)
The
ConcurrentBag<T>
does not provide the functionality that you are looking for. It's not a list, it's a bag. You can't control the order of its contents, and you can't even remove a specific item from this collection. All that you can do is toAdd
orTake
an item.The rich functionality that you are looking for is not offered by any concurrent collection. Your best bet is probably to use a normal
List<T>
protected with alock
. Just make sure that you never touch theList<T>
outside of a protected region. Whether you need toAdd
, orInsert
, orRemove
, or enumerate, or read an item, or read theCount
, or anything else, you must always do it inside alock
region that is locked with the same object.As a side note, it is quite likely that what you are trying to do is fundamentally wrong. There is a reason that the functionality you are asking for is not available: It's practically impossible to use it in a meaningful way without introducing race-conditions. For example two threads could independently figure out that they must insert a new item in the index 5, based on the existing values in the list, and then both try to inserting it at this index, concurrently. Both will succeed, but one of the two items will end-up in the index 6 after being pushed by the other item, and the two items might not be in the correct order in respect to each other.