Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should AddRange() return a list

Tags:

c#

linq

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?

like image 857
finoutlook Avatar asked Dec 07 '22 07:12

finoutlook


2 Answers

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.

like image 152
nvoigt Avatar answered Dec 09 '22 14:12

nvoigt


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.

like image 36
pingoo Avatar answered Dec 09 '22 15:12

pingoo