4

我想用参数更改 where 子句。示例我有 2 个字符串变量。

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

我想根据“string userField="Name"/”更改用户属性(a.Name)

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

我的代码如下所示:

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) }),
               }; 

我怎么能用这个 lambda 表达式做到这一点?

4

4 回答 4

3

您可以尝试以下方法:

.Where(u => (userField == "ID" && u.Id == searchText)
       || (userField == "Name" && u.Name == searchText)
       || (userField == "Email" && u.Email == searchText)
       )
于 2013-07-28T12:43:09.693 回答
2

在这种情况下,我更喜欢扩展方法语法,并这样做:

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.
           )
};
于 2013-07-28T12:29:04.257 回答
1

由于您想动态创建 where 子句,我建议您使用Dynamic LINQ。它允许您动态创建 where 子句。

于 2013-07-28T12:32:37.833 回答
1

动态解决方案

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);
于 2013-07-28T12:56:00.140 回答