简体   繁体   中英

Neglect variable from Query in entity framework where condition C#

public ActionResult sortFilteredItem(string sortByValue,string brand,string category,int price=0 )
{
  var sortedData = (dynamic)null;
  if (sortByValue != "")
  {
    if(sortByValue == "ltoh")
    {
      sortedData = DB.Prouducts.where(x=> x.brandName == brand & x.catName == category & x.price == price).ToList();
    }

  }
 return View(sortedData);
}

how i can neglect if price=0 from query means that it does not make any impact on EF query because if price=0 the query does not returning expected output.Because i have not any record that has 0 price so the query is always returning null .

if(price != 0)
{
    sortedData = DB.Prouducts.where(x=> x.brandName == brand & x.catName == category & x.price == price).ToList();
}
else
{
    sortedData = DB.Prouducts.where(x=> x.brandName == brand & x.catName == category).ToList();
}

i have tried like this it is working good but that is lengthy process.if i have 4 or 5 more variable that,s optional so it is necessary to check null value first for working.Any recommendation ?

You can use the fllowing logic;

sortedData = DB.Prouducts.where(x=> x.brandName == brand 
    && x.catName == category 
    && (price == 0 || x.price == price)) //use this approach for every optional param
    .ToList();

What you can do is apply filters only if the condition holds. Let's say you need to check catName and price. So:

var query = DB.Prouducts.Where(x=> x.brandName == brand);
if (category != null)
{
     query = query.Where(x => x.catName == category);
}

if (price != 0)
{
    query = query.Where(x => x.price == price)
}

sortedData = query.ToList();

Obviously you'll need one "if" per filter, but it is much better than considering all possible combinations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM