简体   繁体   中英

Lambda Expression if-else statement in where clauses

I want to change where clauses with paremeter.Example i have 2 string variable.

string searchText="John";
string userField="Name"//it can be ID,UserName or Email

I want to change Users property(a.Name) based on "string userField="Name"/"

var a entities.Users
     where a.Name==searchText    //a.Name(Name) is declared in userField. It can be ID,UserName or Email                     

My code is shown below:

var users = new
               {
                   total = 10,
                   page = page,
                   record = (entities.Users.Count()),
                   rows = (from user in entities.Users
                           select new
                           {
                               ID = user.ID,
                               Name = user.Name,
                               UserName = user.UserName,
                               UserType = user.Role.Name,
                               Email = user.Email,
                               CreatedDate = user.CreatedDate,
                               UpdatedDate = user.UpdatedDate
                           }).AsEnumerable().Select(m => new { ID = m.ID, Name = m.Name, UserName  = m.UserName, Email = m.Email, UserType = m.UserType, CreatedDate = String.Format("{0:d/M/yyyy  HH:mm:ss}", m.CreatedDate), UpdatedDate = String.Format("{0:d/M/yyyy HH:mm:ss}", m.UpdatedDate) }),
               }; 

How can i do that with this lambada expression?

You may try the following:

.Where(u => (userField == "ID" && u.Id == searchText)
       || (userField == "Name" && u.Name == searchText)
       || (userField == "Email" && u.Email == searchText)
       )

I would prefer extension method syntax in this situation and do it like so:

IQueryable<User> query = entities.Users;
switch (userField)
{
    case "ID":
        int searchID;
        if (int.TryParse(searchText, out searchID))
            query = query.Where(u => u.ID == searchID);
        else
            query = query.Where(u => false);
        break;

    case "Name":
        query = query.Where(u => u.Name == searchText);
        break;

    case "Email":
        query = query.Where(u => u.Email == searchText);
        break;
}

var users = new
{
    total = 10,
    page = page,
    record = (entities.Users.Count()),
    rows = (from user in query
            select new
            // etc.
           )
};

as you want to create your where clauses dynamically i would recommend you to use Dynamic LINQ . It allows you to create where clauses dynamically.

Dynamic solution

string searchText="John";
string userField= "Name";

/* I leave it as an exercixe to add the TypeConversion if Id is Int */
ParameterExpression pe = Expression.Parameter(typeof(User),"usr");
Expression left = Expression.Property(pe, typeof(User).GetProperty(userField));
Expression right = Expression.Constant(searchText);
Expression equ = Expression.Equal(left, right);

var whereExpr = Expression.Lambda<Func<User, bool>>(
      equ, 
      new ParameterExpression[] { pe });

var a =  entities.Users.Where(whereExpr);

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