In the following code:
var cats = new List<string>() {"cat1", "cat2"};
var dogs = new List<string>() {"dog1", "dog2"};
var animals = new List<Animal>();
animals = (cats.Select(x => new Animal() {Type = "Cat", Name = x}).ToList().AddRange(
dogs.Select(x => new Animal() {Type = "Dog", Name = x}).ToList())).ToList();
Calling the ToList() at the end is an error, because AddRange() returns void. This doesn't seem right nowadays when using Linq type queries.
I found I could change it to .Union()
or .Concat()
to fix the issue, but shouldn't AddRange()
be updated, or is there a reason for it returning void?
AddRange
changes the underlying List object. No LinQ method does that. So it's fundamentally different and should not be used in a LinQ concatination. It's return value of void
reflects that.
You've answered your own question. If you want distinct values from the two lists use Union, if you want to just join the two lists use Concat. Once the two enumerable have been joined you can call ToList().
AddRange is a method on the List its self and isn't anything to do with LINQ.
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