Joao Raposo
Joao Raposo

Reputation: 145

Blocking collection - Remove a specific element

I'm using a blocking collection as I need this list to be thread safe:

Orders = new BlockingCollection<Order>();

I'm trying to remove a specific order, lets say I want to remove order.ID 1

if it was a normal collection would be something like

orders.Remove(orders.Where(o => o.ID == 1).First());   

I've read about those collections there is Take() and TryTake() but none of them allows me to specify which one I want to remove.

Upvotes: 1

Views: 1936

Answers (1)

CodesInChaos
CodesInChaos

Reputation: 108810

You could use a ConcurrentDictionary<int, Order>. In particular its TryRemove method takes an ID, removes the entry, and returns the Order.

This collection is thread safe, but non blocking. As with Dictionary<TKey, TValue> keys must be unique (your use of First instead of Single suggest that constraint might be violated in your case).

Upvotes: 5

Related Questions