在where子句中使用lambda Expression if-else语句

时间:2013-07-28 12:09:46

标签: c# asp.net-mvc linq entity-framework

我想用paremeter更改where子句。例如我有2个字符串变量。

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

我想根据“string userField =”Name“/”

更改Users属性(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) }),
               }; 

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

4 个答案:

答案 0 :(得分:3)

您可以尝试以下方法:

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

答案 1 :(得分: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.
           )
};

答案 2 :(得分:1)

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

答案 3 :(得分:1)

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