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:
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.
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