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!
e.ToList<T>()is implemented under the hood as:And the
List<T>(IEnumerable<T> e)constructor actually just callsthis.AddRange(e)internally.In other words, the two bits of code will do the exact same thing, in the exact same way.