locked
LINQ Select Question RRS feed

  • Question

  • User-507786106 posted

    I am selecting from employee table, where I get all employees active or not and sometimes I need only true. 

    This is my code, can I simplify this code more efficiently?

    if (isActive == false)

    {

          var data = from emp in db.employee where (emp.Responsible == true)

           select (new SelectListIem{ text = emp.firstname + "  "  + emp.lastname, Value = emp.Id.ToString()});   //note will return all employees with Responsible == true

    }else

    {

               var data = from emp in db.employee where ((emp.Responsible == true) &&  (Active == true)

              select (new SelectListIem { text = emp.firstname + "  "  + emp.lastname, Value = emp.Id.ToString()});      //Will return ONLY Responsible == True AND Active == True

    }

    I would like to combine both statements, and based on the parameters isActive, the linq statement executes.  The employee must have Responsible == True for both conditions.

    Is there a better why to write this code in Linq without duplicating the statement?

    Monday, August 12, 2019 1:59 PM

Answers

  • User475983607 posted

    This should work.

    bool isActive = true; //false
    var query = db.employee.Where(emp => emp.Responsible);
    if(isActive) 
    {
    	query.Where(emp.Active == isActive)
    }
    

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, August 12, 2019 3:06 PM

All replies

  • User475983607 posted

    It looks like this will work.

    bool isActive = true; //false
    var query = db.employee.Where(emp => emp.Responsible && emp.Active == isActive);

    From there you should be able to populate the List<SelectListItem>.

    Monday, August 12, 2019 2:10 PM
  • User-507786106 posted

    Yes, that works for Active and Inactive list but I knew the following:

    if isActive ==  true only show the true list

    if isActive == false show all (both true and false)

    Is this possible in one statement or should I create two different statements.?

    Monday, August 12, 2019 2:24 PM
  • User475983607 posted

    This should work.

    bool isActive = true; //false
    var query = db.employee.Where(emp => emp.Responsible);
    if(isActive) 
    {
    	query.Where(emp.Active == isActive)
    }
    

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, August 12, 2019 3:06 PM
  • User1520731567 posted

    Hi slimbunny,

    You could also use WhereIf,like this extension method.

    For example:

      var query =db.employee
    .WhereIf(p => p.Responsible==true, isActive==false) .WhereIf(p => p.Responsible==true && p.Active==true, isActive==true);

    More details,you could refer to this link:

    https://stackoverflow.com/a/33153996/11741806

    Best Regards.

    Yuki Tao

    Tuesday, August 13, 2019 6:27 AM