如果在linq内声明

时间:2014-05-03 10:53:43

标签: linq

是否可以在此linq查询中包含if语句...例如,如果viewModel.Sessionstateadminroot.CourseSearchPara == null不使用where子句,只需获取所有记录?

 viewModel.Courseroot = (from course in container.Courses
                                        where course.Description == viewModel.Sessionstateadminroot.CourseSearchPara
                                        orderby course.Name descending
                                        select new Course_() { Name = course.Name, Description = course.Description, Guid = course.Guid, CourseID = course.CourseID }).Skip((int)skip).Take(take).ToList();

1 个答案:

答案 0 :(得分:2)

您可以使用||运算符:

viewModel.Courseroot = (from course in container.Courses
                                        where viewModel.Sessionstateadminroot.CourseSearchPara == null
                                        || course.Description == viewModel.Sessionstateadminroot.CourseSearchPara
                                        orderby course.Name descending
                                        select new Course_() { Name = course.Name, Description = course.Description, Guid = course.Guid, CourseID = course.CourseID }).Skip((int)skip).Take(take).ToList();

因为||运营商正在短路,如果第一部分是真的,第二部分就不会被发现。

或者您可以逐步构建查询:

IEnumerable<Course> query = container.Courses;
if (viewModel.Sessionstateadminroot.CourseSearchPara != null)
    query = query.Where(course => course.Description == viewModel.Sessionstateadminroot.CourseSearchPara)
viewModel.Courseroot = query
    .Select(course => new Course_() { Name = course.Name, Description = course.Description, Guid = course.Guid, CourseID = course.CourseID })
    .Skip((int)skip)
    .Take(take)
    .ToList();