Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Convert IEnumerable<T> to ConcurrentBag<T> in C#?

Tags:

c#

c#-4.0

My linq query returns a collection of IEnumerable<object>.

How can I convert this into a strongly typed object of collection ConcurrentBag<object> ?

like image 349
Princeton Avatar asked Sep 20 '10 07:09

Princeton


4 Answers

ConcurrentBag has a constructor that takes an IEnumerable.

IEnumerable<T> myEnum = ...
ConcurrentBag<T> myBag = new ConcurrentBag<T>(myEnum);
like image 57
NullUserException Avatar answered Nov 20 '22 15:11

NullUserException


You could use the proper constructor.

IEnumerable<Foo> foos = ...
ConcurrentBag<Foo> concurrentFoos = new ConcurrentBag<Foo>(foos);
like image 26
Darin Dimitrov Avatar answered Nov 20 '22 16:11

Darin Dimitrov


ConcurrentBag<T> has a constructor that takes an IEnumberable<T> as input.

Several collections support this, so make sure to check the constructor overloads.

like image 11
Brian Rasmussen Avatar answered Nov 20 '22 16:11

Brian Rasmussen


Here is the extension method:

public static ConcurrentBag<T> ToConcurrentBag<T>(this IEnumerable<T> source) => new ConcurrentBag<T>(source);
like image 1
AsValeO Avatar answered Nov 20 '22 16:11

AsValeO