I make a query to the database, first I take the data from the Technologies table, then there is a search, sorting + paginating. It turns out a lot of similar code.

 switch (sort) { case "Low": items.Tvsets = db.Technologies.Where(x => x.Name.Contains(tech)) .Include(p => p.Tvsets.Select(x => x.Company)) .FirstOrDefault() ? .Tvsets .Where(x => x.Name.Contains(search) || x.Company.Name.Contains(search) || x.Technology.Name.Contains(search)) .OrderBy(x => x.Price) .Skip((pageInfo.PageNumber - 1) * pageInfo.PageSize) .Take(GetAll(pageInfo.TotalItems, pageInfo.PageSize, pageInfo.PageNumber)) .ToList(); return View(items); default: ViewBag.Sort = "High"; items.Tvsets = db.Technologies.Where(x => x.Name.Contains(tech)) .Include(p => p.Tvsets.Select(x => x.Company)) .FirstOrDefault() ? .Tvsets .Where(x => x.Name.Contains(search) || x.Company.Name.Contains(search) || x.Technology.Name.Contains(search)) .OrderByDescending(x => x.Price) .Skip((pageInfo.PageNumber - 1) * pageInfo.PageSize) .Take(GetAll(pageInfo.TotalItems, pageInfo.PageSize, pageInfo.PageNumber)) .ToList(); return View(items); } 

How can I reduce the code? Maybe there are any patterns or other ways?

  • 2
    Please note that you are dragging the entire Tvsets collection from the DBMS onto the client without filtering on the base side. Considering that there are enough records to break them into pages - this is a gross mistake. - Pavel Mayorov

1 answer 1

try this:

 var tvSets = db.Technologies .Where(x => x.Name.Contains(tech)) .Include(p => p.Tvsets.Select(x => x.Company)) .FirstOrDefault() ? .Tvsets .Where(x => x.Name.Contains(search) || x.Company.Name.Contains(search) || x.Technology.Name.Contains(search)).AsQueryable(); if (sort == "Low") { tvSets = tvSets.OrderBy(x => x.Price); } else { ViewBag.Sort = "High"; tvSets = tvSets.OrderByDescending(x => x.Price); } items.Tvsets = tvSets.Skip((pageInfo.PageNumber - 1) * pageInfo.PageSize) .Take(GetAll(pageInfo.TotalItems, pageInfo.PageSize, pageInfo.PageNumber)) .ToList(); return View(items); 

Those. We distinguish the common in both requests, and the difference depending on the parameter. In this case, you have only one difference in sorting. Here it is allocated. The request will not be executed until .ToList () is called. Until then, it can be collected in pieces, without fear that the server will leave a piece of the request.

  • Thank you This is exactly what I need! Special thanks for the clarification. - Nikita
  • 2
    The explanation about the "request will not be executed until you have done ToList " is incorrect. FirstOrDefault executes the query just as successfully! - Pavel Mayorov
  • Yes. Missed this moment. Thank you - Hemid Abbasov