Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Object Collection to another Object Collection without iterating [duplicate]

I have a collection of objects objcol1(example Collection of cities in a state) and another object collection objcol2(example collection of cities in a country). Now I am querying for objcol1 and I want to add it to objcol2. I can do this by iterating through objcol1 and adding one by one to objcol2 but can I directly add objcol1 to objcol2 like objcol2.add(objcol1);

Can anyone tell me whether it is possible without iterating? If yes please explain me the process

like image 206
Deepak Avatar asked Feb 29 '12 01:02

Deepak


4 Answers

You could use the Enumerable.Concat extension method:

objcol1 = objcol1.Concat(objcol2)

I'm sure under the covers somewhere it actually iterates, but you won't need to write the code to do it.

NOTE: This will only work if your City objects are the same, alternatively you could use Select to map the objects.

like image 198
M.Babcock Avatar answered Nov 15 '22 20:11

M.Babcock


You can also use AddRange of the List. See documentation for more information.

var a = new List<string> { "1", "2" };
var b = new List<string> { "3", "4" };
a.AddRange(b);

// a would contain "1", "2", "3" and "4"
like image 27
Tx3 Avatar answered Nov 15 '22 22:11

Tx3


Yes, it is possible depending upon your use case. If you don't care what the "collection" type is, then you can use the linq Concat command to create a new enumerable that, when iterated, will include items from both collections.

var collection1 = new List<int> { 1, 2, 3 };
var collection2 = new [] { 4, 5, 6};

var concatenated = collection1.Concat(collection2);

If, on the other hand, you need to actually insert the items into the existing collection, you'll need to iterate.

like image 23
Craig Wilson Avatar answered Nov 15 '22 21:11

Craig Wilson


Actually, you don't need a new var:

collection1.AddRange(collection2);
like image 28
Faust Avatar answered Nov 15 '22 21:11

Faust