Using where all on linq

本文关键字:linq on all where Using | 更新日期: 2023-09-27 18:15:52

我正试图为我的应用程序实现搜索功能,但我想要发生的是发送所有列表,如果没有指定关键字,我有一个where子句。

下面是我的动作:

Public ActionResult classes(string keyword ="")
{
        EmployeeContext emp = new EmployeeContext();
        List<classlist> asd = (from subj in emp.Subjects
                               join prof in emp.professors on subj.id equals prof.id
                               join dep in emp.departments on prof.id equals dep.id
                               where subj.subj == keyword
                               select new classlist()
                               {
                                   id = subj.id,
                                   subj = subj.subj,
                                   days = subj.days,
                                   cstart = subj.cstart,
                                   cend = subj.cend,
                                   units = subj.units,
                                   fname = prof.fname,
                                   lname = prof.lname,
                                   status = prof.status,
                                   department = dep.dname,
                                   isSelected = false
                               }).ToList();
        return View(asd);
}

我研究了一下,上面说要用'ALL',但它不起作用。我不想做一个if else语句取决于关键字是否为空,因为这将使我的代码丑陋。subj属性是主题的名称。

Using where all on linq

你可以这样做

where subj.subj == keyword || keyword==""

或者这个,这样你就不需要单独的where

from subj in emp.Subjects.Where(x=>x.subj == keyword || keyword=="")
join prof in emp.professors.....

除了@DarkKnight提供的答案之外,您还可以利用这样一个事实,即查询实际上没有执行,直到您用ToList实现它,所以您可以这样做:

public ActionResult classes(string keyword ="")
{
    EmployeeContext emp = new EmployeeContext();
    IEnumerable<classlist> asd = (from subj in emp.Subjects
                           join prof in emp.professors on subj.id equals prof.id
                           join dep in emp.departments on prof.id equals dep.id
                           select new classlist()
                           {
                               id = subj.id,
                               subj = subj.subj,
                               days = subj.days,
                               cstart = subj.cstart,
                               cend = subj.cend,
                               units = subj.units,
                               fname = prof.fname,
                               lname = prof.lname,
                               status = prof.status,
                               department = dep.dname,
                               isSelected = false
                           });
    //Apply the where clause if required
    if(!string.IsNullOrEmpty(keyword))
        asd = asd.Where(c => c.subj == keyword);
    //Return the materialised list now:
    return View(asd.ToList());
}

你为什么要这样做?

  1. 你可能经常有一个更复杂的where子句要应用,这种方式更容易编码。
  2. 这个方法可能稍微更有效,因为复合where子句在不需要时不被传递到您的数据存储。