Reputation:
I have three fields that I want to base on them filter my result. I used an if-else statement, but it is very awkward, and base on my fields, I had to write some if blocks statements. Is there an easier way to do this?
public ActionResult Search(String title, int? category_id, string productCode)
{
IEnumerable<products> result;
using (DBModels db = new DBModels())
{
if (title != null && category_id == null && productCode == null)
{
result = db.products.Where(c => c.title.Contains(title))
.Include(x => x.media)
.Include(p => p.categories)
.ToList();
return View(result);
}
else if (category_id != null && title == null && productCode == null)
{
result = db.products.Where(c => c.category_id == category_id)
.Include(x => x.media)
.Include(p => p.categories)
.ToList();
return View(result);
}
else if (productCode != null && title == null && category_id == null)
{
result = db.products.Where(c => c.id.ToString().Contains(productCode))
.Include(x => x.media)
.Include(p => p.categories)
.ToList();
return View(result);
}
else if (productCode != null && title != null && category_id != null)
{
result = db.products.Where(c => c.title.Contains(title)
&& c.category_id == category_id
&& c.id.ToString().Contains(productCode))
.Include(x => x.media)
.Include(p => p.categories)
.ToList();
}
}
result = db.products.Where(c => c.title.Contains(title)
|| c.category_id == category_id
|| c.id.ToString().Contains(productCode))
.Include(x => x.media)
.Include(p => p.categories)
.ToList();
return View(result);
}
Upvotes: 0
Views: 342
Reputation: 771
You can use IQueryable
public ActionResult Search(string title, int? category_id, string productCode)
{
IEnumerable<products> result;
using (DBModels db = new DBModels())
{
var query = db.products
.Include(x => x.media)
.Include(p => p.categories)
.AsQueryable();
if (!string.IsNullOrWhiteSpace(title))
{
query = query.Where(c => c.title.Contains(title));
}
if ( category_id != null)
{
query = query.Where(c => c.category_id == category_id);
}
if (!string.IsNullOrWhiteSpace(productCode))
{
query = query.Where(c => c.id.ToString().Contains(productCode));
}
result = query.ToList();
return View(result);
}
}
Upvotes: 5