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
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.
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"
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.
Actually, you don't need a new var:
collection1.AddRange(collection2);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With