Home > Software engineering >  How to copy BlockingCollection and edit the new one without editing the origin
How to copy BlockingCollection and edit the new one without editing the origin

Time:04-28

I want to copy a BlockingCollection and edit the copy.

(dataModelCollection is the copy of DataModelListRaw)

When I do this:

BlockingCollection<DataModel> dataModelCollection = DataModelListRaw;
while (dataModelCollection.TryTake(out _)) { }

I clear also the origin, because of the reference.

If I fill the new BlockingCollection item for item, like this:

BlockingCollection<DataModel> dataModelCollection = new();

    foreach(var datamodel in DataModelListRaw)
    {
        dataModelCollection.Add(datamodel);
    }

while (dataModelCollection.TryTake(out _)) { }

it works.

But is there a shorter and more elegant way to do this copy? Maybe a method in BlockingCollection?

CodePudding user response:

Just do

var myCopy = dataModelCollection.ToList();

This will use the IEnumerable interface to iterate over the collection and copy all the items. You can then do any editing of the list you need. If you need an actual blocking collection you need to create a new one:

var blockingCollectionCopy = new BlockingCollection<DataModel>(new ConcurrentQueue<DataModel>(myCopy ));
  • Related