Lambda表达式

时间:2016-10-05 07:30:45

标签: c# asp.net asp.net-mvc lambda where-clause

我在Controller项目的ASP.NET MVC中有一些过滤器参数,我需要根据这些参数动态创建Where子句。如果isActive参数为true,则会获得具有StatusId = 1的记录。方法中还有userNamelabId个参数,应在Where子句中匹配。

public ActionResult GetStudents(int labId, string userName, bool isAll)
{
    var allRecords = repository.Students;
    //If isAll, get all the records having StatusId = 1
    var result = allRecords.Where(m => (isAll) || m.StatusId == 1); 
    //??? 
}

我使用上面的过滤器,但我不知道什么是多个参数最合适的方式(约定),以便快速获取结果。有什么想法吗?

注意:我希望过滤所有三个参数,并且Where子句应根据参数的值包含所有组合(也为null或空)。

4 个答案:

答案 0 :(得分:2)

你可以连接linq方法,因为它们都返回IEnumerable<T>并使用类似SQL的东西组合 - And(依赖于你使用的LINQ提供者):

IEnumerable<Student> result = allRecords;
if(labelId.HasValue) 
    result = result.Where(x => x.LabelId == labelId);
else
    result = result.Where(x => x.LabelId == 0); // or whatever your default-behaviour is

if(isAll)
    result = result.Where(x => x.StatusId == 1);
else 
    result = result.Where(x => x.StatusId == 0); // or whateever your default-behaviour is when isAll is false

if(!String.IsNullOrEmpty(userName)) 
    result = result.Where(x => x.Name == userName);
else 
    result = result.Where(x => x.Name == "Claus"); // or whatever the default-behaviour is when the param isn´t set

答案 1 :(得分:2)

LOS=true

您可以使用predicate builder

答案 2 :(得分:1)

这样做

public ActionResult GetStudents(int labId, string userName, bool isAll)
{
    var allRecords = repository.Students;
    //If isAll, get all the records having StatusId = 1
    if (isAll) 
    { 
       var result = allRecords.Where(m => m.StatusId == 1  && m.UserName == userName  && m.LabId == labId); 
    } 
    else 
    { 
       // do else things
    }
}

答案 3 :(得分:1)

你需要类似下面的内容

public ActionResult GetStudents(int labId, string userName, bool isAll)
{
    var allRecords = repository.Students;
    //If isAll, get all the records having StatusId = 1
    if (isAll) 
    { 
        var result = allRecords.Where(m => m.StatusId == 1 
                                            && m.LabId == labId 
                                            && m.UserName == username);
        //or
        var result = from record in allRecords
                         where record != null &&
                               record.StatusId == 1
                               && !string.IsNullOrWhiteSpace(record.UserName)
                               && record.UserName.Equals(username)
                               && record.Labid = labId
                         select record;
    } 
    else 
    { 
       // do else things
    }
}