Garrison Neely
Garrison Neely

Reputation: 3289

Is there any benefits to using List.AddRange over a LINQ.ToList()?

I was working through an MVC4 tutorial today and saw the user implemented a select in a different manner than I'm used to. His code was:

var GenreLst = new List<string>(); 

var GenreQry = from d in db.Movies 
               orderby d.Genre 
               select d.Genre; 
GenreLst.AddRange(GenreQry.Distinct()); 
ViewBag.movieGenre = new SelectList(GenreLst); 

I looked at it and rewrote it in my own way as:

var genres = db.Movies
            .OrderBy(m => m.Genre)
            .Select(m => m.Genre)
            .Distinct()
            .ToList();

ViewBag.MovieGenre = new SelectList(genres);

His GenreList variable isn't used elsewhere, so I got rid of it. My main question is how he uses the AddRange. Is it any better to AddRange than ToList?

Thanks for reading!

Upvotes: 6

Views: 4293

Answers (1)

cdhowie
cdhowie

Reputation: 168988

e.ToList<T>() is implemented under the hood as:

return new List<T>(e);

And the List<T>(IEnumerable<T> e) constructor actually just calls this.AddRange(e) internally.

In other words, the two bits of code will do the exact same thing, in the exact same way.

Upvotes: 21

Related Questions