Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# concat two Collection<string> using linq and getting a Collection<string> result

I'm trying to do this:

var collection1 = new Collection<string> {"one", "two"};
var collection2 = new Collection<string> {"three", "four"};

var result = collection1.Concat(collection2);

But the result variable is type Enumerable[System.String] , whereas I want a Collection[System.String]

I've tried casting:

var all = (Collection<string>) collection1.Concat(collection2);

But no joy.

like image 908
Lance Rushing Avatar asked Aug 25 '10 18:08

Lance Rushing


2 Answers

var result = new Collection<string>(collection1.Concat(collection2).ToList());

For some reason System.Collections.ObjectModel.Collection requires an IList parameter to it's constructor. (The other collections only need an IEnumerator)

like image 89
James Curran Avatar answered Sep 28 '22 00:09

James Curran


Use Enumerable.ToList(), as List<> is an ICollection<>.

E.g.:

IList list = a.Concat(b).ToList()

If you meant System.ObjectModel.Collection<> then you will have to pass the created list into the constructor of Collection<>, not ideal I know.

var collection = new System.ObjectModel.Collection<string>(a.Concat(b).ToList());
like image 36
Paul Ruane Avatar answered Sep 28 '22 02:09

Paul Ruane