How to Insert in ConcurrentBag at specified Index and retaining all values?

1.8k views Asked by At

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)

1

There are 1 answers

7
Theodor Zoulias On BEST ANSWER

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 to Add or Take 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 a lock. Just make sure that you never touch the List<T> outside of a protected region. Whether you need to Add, or Insert, or Remove, or enumerate, or read an item, or read the Count, or anything else, you must always do it inside a lock 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.