Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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!

like image 642
Garrison Neely Avatar asked Jul 18 '12 17:07

Garrison Neely


1 Answers

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.

like image 143
cdhowie Avatar answered Oct 23 '22 06:10

cdhowie