Add Object Collection to another Object Collection without iterating

.net c# entity-framework linq

Question

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

1
6
2/29/2012 1:34:27 AM

Accepted Answer

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.

15
1/26/2017 10:06:28 PM

Popular Answer

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"


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow