How to Convert Concurrentbag to List?

How to Convert Concurrentbag to List?

I have few task which I can do in parallel. As list is not thread safe i am using concurrentbag. Once all the task are completed I want to convert the concurrentbag to list.

I have searched in MSDN but couldn't find any API which can convert concurrentbag to list in c#. How can I do it?

Note: i have to convert to list, It is necessary.

I have other option to apply lock on list but i wanted to use in build concurrentbag which is thread safe.

5

5 Answers

You could use ToList extension method.

var list = concurrentBag.ToList();

ConcurrentBag has the extension method of .ToList() - it implementsIEnumerable<T>

var someList = someConcurrentBag.ToList();

ConcurrentBag has the ToList() method.

If your internal item are non list then use

var someList = someConcurrentBag.ToList();

Or you can try as below If each item in the cbag is already a list.

E.g. In my case ConcurrentBag<List<int>>

ConcurrentBag<List<string>> jobErrorsColl = new ConcurrentBag<List<string>>();

// Got something in jobErrorsColl
List<string> multipleJobErrors = new List<string>();
List<string> singleJobErrors = new List<string>();

while (jobErrorsColl.IsEmpty)
{
    jobErrorsColl.TryPeek(out singleJobErrors);
    multipleJobErrors.AddRange(singleJobErrors);
}

return multipleJobErrors;  

MSDN link is here for the same

You can use the following to convert concurrentbag to list:

var list = = someConcurrentBag.SelectMany(r => r).ToList();
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

James H. Sterling
Author

James H. Sterling

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.