I'm filtering the results of a list of items in LINQ, I have seen two methods of doing it and wondered which (if any) is better. One is the method I came up with after playing around with the Intellisense, the other is from the ASP.NET MVC tutorial (found here)
My method
// GET: ProductVersions
public ActionResult Index(string productName)
{
var productVersions = db.ProductVersions.Include(p => p.LicenceVersion).Include(p => p.Product);
if (!string.IsNullOrEmpty(productName))
{
productVersions = productVersions.Where(s => s.Product.Name == productName);
}
return View(productVersions.ToList());
}
Tutorial Method
public ActionResult Index(string movieGenre)
{
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);
var movies = from m in db.Movies
select m;
if (!string.IsNullOrEmpty(movieGenre))
{
movies = movies.Where(x => x.Genre == movieGenre);
}
return View(movies);
}
My questions
- Is there a notable difference in performance, particularly as the second option is quite verbose
- Is there a stylistic convention that I am missing by using my method
- Is there any other possible advantage to using the second method
~Edit~
Turns out I need the ViewBag data in order to be able to populate a dropdown filter on the front end (more's the pity), so my actual code worked out as follows:
// GET: ProductVersions
public ActionResult Index(string productName)
{
//Get list of product names to filter by
var ProductLst = new List<string>();
var ProductQry = from pv in db.ProductVersions
orderby pv.Product.Name
select pv.Product.Name;
ProductLst.AddRange(ProductQry.Distinct());
ViewBag.productName = new SelectList(ProductLst);
//Populate product versions
var productVersions = db.ProductVersions.Include(p => p.LicenceVersion).Include(p => p.Product);
//Filter by product name
if (!string.IsNullOrEmpty(productName))
{
productVersions = productVersions.Where(s => s.Product.Name == productName);
}
return View(productVersions.ToList());
}