簡體   English   中英

Lambda表達式中的動態Where子句

[英]Dynamic Where clause in Lambda expression

我在ASP.NET MVC項目的Controller中有一些過濾器參數,並且需要根據這些參數動態創建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或為空)。

您可以連接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
var predicate = PredicateBuilder.False<Record>();

if(isAll)
  predicate = predicate.AND(d => d.StatusId ==1);

 predicate = predicate.AND(d => d.labID == labid && d.username = username);

 return allRecords.Where(predicate);`

您可以使用謂詞構建器

像這樣

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
    }
}

你需要像下面這樣的東西

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
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM