How to combine items from two ConcurrentBags?

1.1k Views Asked by At

For Lists I could use the Union method:

var finalCollection = new List<MyType>();
var list1= new List<MyType>();
var list2 = new List<MyType>();
finalCollection = list1.Union(list2).ToList();

But when I try to do the same with ConcurrentBags,

var finalCollection = new ConcurrentBag<MyType>();
var bag1= new ConcurrentBag<MyType>();
var bag2= new ConcurrentBag<MyType>();
finalCollection = bag1.Union(bag2);

I get:

Cannot implicitly convert type "System.Collections.Generic.IEnumerable< MyType>" to "System.Collections.Concurrent.ConcurrentBag"

2

There are 2 best solutions below

6
On

Perhaps the problem is you are trying to Union the elements into a new ConcurrentBag

What you actually get after the union is an IEnumerable of MyType

To get back a ConcurrentBag try doing it like so:

var bag1 = new ConcurrentBag<MyType>();
var bag2 = new ConcurrentBag<MyType>();
var finalCollection = new ConcurrentBag<MyType>(bag1.Union(bag2));
2
On

The var in...

var finalCollection = new ConcurrentBag<MyType>();

...might be hiding what the problem is. Expanding it (mentally or explicitly) to...

ConcurrentBag<MyType> finalCollection = new ConcurrentBag<MyType>();

...should make it clear why bag1.Union(bag2), which returns an IEnumerable<MyType>, can't be assigned to finalCollection. Note that in Visual Studio (Code) if you hover the mouse over the var keyword a tooltip will show you the variable's inferred type.

Also, your two code snippets aren't quite "the same"; in the first you are calling ToList() to create a List<> from the result of Union(), but in the second you trying to assign the result of Union() directly to a ConcurrentBag<> variable without doing anything to actually make it a ConcurrentBag<>, which the other answer shows how to do. If you removed the .ToList() from the first code snippet you would get a similar error.