Reputation: 1093
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?
Upvotes: 4
Views: 6163
Reputation: 42453
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);
Upvotes: 1
Reputation: 18411
You may try the following:
.Where(u => (userField == "ID" && u.Id == searchText)
|| (userField == "Name" && u.Name == searchText)
|| (userField == "Email" && u.Email == searchText)
)
Upvotes: 3
Reputation: 32681
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.
Upvotes: 1
Reputation: 177153
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.
)
};
Upvotes: 2