I have some filter parameters in the Controller of an ASP.NET MVC project and I need to create Where clause dynamically according to these parameters. If isActive parameter is true, it will get the records having the StatusId = 1. There are also userName and labId parameters in the method that should be matched in the Where clause.
public ActionResult GetStudents(int labId, string userName, bool isAll)
{
var allRecords = repository.Students;
//If isAll, get all the records having StatusId = 1
var result = allRecords.Where(m => (isAll) || m.StatusId == 1);
//???
}
I use the filter above, but I have no idea what is the most suitable way (conventions) for multiple parameters in order to fetch the result fast. Any idea?
Note: I want to filter for all of three parameters and Where clause should contain all of the combinations according to the parameter's values (also is null or empty).
if (isAll) { allRecords = allRecords.Where(m => m.StatusId == 1; } else { ..}Whereclauses are joined together by ands. So you can add them as you need as @StephenMuecke showed.userNameif that is notnull? in which case addif (userName != null) { allRecords = allRecords.Where(...); }userNamecan benull, then you need the 3ifclauses (othewise.Where(x => x.UserName == userName)would return no records.UserName == userName? And what aboutlabId- does you model have a property for that, and can its value be0?