Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 517
ftdeveloper Avatar asked Mar 23 '23 00:03

ftdeveloper


2 Answers

You may try the following:

.Where(u => (userField == "ID" && u.Id == searchText)
       || (userField == "Name" && u.Name == searchText)
       || (userField == "Email" && u.Email == searchText)
       )
like image 142
Giannis Paraskevopoulos Avatar answered Apr 05 '23 23:04

Giannis Paraskevopoulos


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.
           )
};
like image 23
Slauma Avatar answered Apr 05 '23 22:04

Slauma