1

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

  1. Is there a notable difference in performance, particularly as the second option is quite verbose
  2. Is there a stylistic convention that I am missing by using my method
  3. 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());
        }
J Lewis
  • 462
  • 1
  • 4
  • 15

3 Answers3

2

It is only the last part of the example code that is comparable to your question - the genre list is something else in the UI that isn't present in your code, and that's fine. So all we are comparing is:

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());

vs

var movies = from m in db.Movies
             select m;

if (!string.IsNullOrEmpty(movieGenre))
{
    movies = movies.Where(x => x.Genre == movieGenre);
}

return View(movies);

These are virtually identical - the main difference is the extra includes in your code, which is fine if you need them.

They are so comparable that there is nothing relevant to talk about in terms of comparisons.

Personally I prefer the ToList() in your example as it forces the data to materialize in the controller rather than the view. A counter to that is that having the view have a queryable allows the view to compose it further. I don't want my view composing queries, but that is a stylistic point.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • I am also trying to avoid my view having any kind of processing, so this is good to know. I'll give it a little while but this is a great answer :) – J Lewis Aug 02 '17 at 08:38
1

The code samples you provided have quite some differences, but assuming you are asking about extension methods syntax vs query syntax, the answers I believe are as follows:

  1. There is no difference in performance. The compiler treats the samples identically.
  2. You are not missing any stylistic convention. I usually find chaining extension methods to be more readable and maintainable
  3. There can be a case made for using query syntax when you want to leverage multiple range variables. Check out this answer: LINQ - Fluent and Query Expression - Is there any benefit(s) of one over other?
raduchept
  • 181
  • 4
  • 11
  • I think that there is a huge diffrence betwen this author example and tutorial example about Eager and Lazy :) In RealTime working you can detect this. :) – Eyup Can ARSLAN Aug 02 '17 at 08:58
  • You are correct, there are multiple differences. I was just assuming from the way he framed his question that he was interested in knowing the differences between extension methods syntax vs query syntax. – raduchept Aug 02 '17 at 10:26
0

I understand that you use Eager Loading. I think EagerLoading is not necessary if your model isn't so complex. For this reason use Layz loading; Also I try to refactor your code. Look at my code style and codeLine count :) This can help for you especially huge class :) H

http://www.entityframeworktutorial.net/EntityFramework4.3/lazy-loading-with-dbcontext.aspx

At the below link you can get detailed Info.

The sample class can translate linke this also

public ActionResult Index(string productName)
{
   if(string.IsNullOrEmpty(productName)) return View(new List<ProductVersions>());
   return View(db.ProductVersions.Where(s => s.Product.Name == productName).ToList());
}

Lastly your comprission is wrong between "your exp and tutorial". Because ViewModel used In TutorialExp. This is usefull to prevent directly DbCon object using by Client's. In my opinion

using(var db=new DbEntities())  

is required for this tutorial.

Eyup Can ARSLAN
  • 692
  • 9
  • 25
  • By the way "Tutorial Method" used "Linq with SqlType query". I prefer to use "Lambada expression with Linq". I think SqlType a bit complexty :) – Eyup Can ARSLAN Aug 02 '17 at 08:45