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.
)
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With