Suppose that you want to create a LINQ query to filter the users of your database based on bool property. Let's say getting inactivated users. You can create expression for that:
private Expression<Func<User, bool>> GetDeactivatedUserExpression(bool deactivated) { if (deactivated == false) { return p => p.Inactive == true; } return p => p.Inactive == false; }
Not that, we just want to filter the output based on a bool parameter. And finally about the usage:
public PagedResult<UserListView> GetPagedUsers(int page, bool deactivated) { var deactivatedExpression = GetDeactivatedUserExpression(deactivated); return _baseDbContext.Users.Where(deactivatedExpression).Select(d => new UserListView { Id = d.Id, Mobile = d.Mobile, CountryCode = d.CountryCode, Username = d.Username, Inactive = d.Inactive, IsVerified = d.IsVerified }).ToPagedResult(page); }
Although in an advance way you can use Specification Pattern, the above one is another simple way. Cheers!