Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to copy BlockingCollection and edit the new one without editing the origin C#

I want to copy a BlockingCollection and edit the copy.

(dataModelCollection is the copy of DataModelListRaw)

When I do this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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 ));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading