将来自同一表的2个查询合并为一个linq查询

时间:2016-09-27 13:37:29

标签: c# asp.net-mvc linq linq-to-sql

我有2个查询查询同一个表,但有不同的参数,我想合并为一个, 查询1

 //ToDo refactor
        int myDayOfWeek = 0;
        DateTime dt = DateTime.Today;
        myDayOfWeek = (int)dt.DayOfWeek;

        var todaysLecture = (from c in _context.LectureGigs.Where(g => g.IsWeekLy == true && (int)g.Days == (myDayOfWeek))
                             select c).ToList();
        //results Ok 1 result

查询2

var upCommingLecture = _context.LectureGigs
            .Include(g => g.Artist).Include(g => g.Genre)
            .Where(g => g.DateTime > DateTime.Now && !g.IsCanceled);
        //results Ok 2 result

我想创建的查询

 var upCommingLecture = _context.LectureGigs
           .Include(g => g.Artist).Include(g => g.Genre).Where(g => g.IsWeekLy == true && (int)g.Days == (myDayOfWeek))
           .Where(g => g.DateTime > DateTime.Now && !g.IsCanceled);
        //Error none but 0 result

我也试过这个

var upCommingLecture = _context.LectureGigs
           .Include(g => g.Artist).Include(g => g.Genre)
           .Where(g => g.DateTime > DateTime.Now && !g.IsCanceled && g.IsWeekLy==true &&(int)g.Days==(myDayOfWeek));
        //Error none but 0 result

1 个答案:

答案 0 :(得分:3)

||),而非 AND &&

var upCommingLecture = _context.LectureGigs
       .Include(g => g.Artist).Include(g => g.Genre)
       .Where(g => (g.DateTime > DateTime.Now && !g.IsCanceled) 
                || (g.IsWeekLy==true &&(int)g.Days==(myDayOfWeek)));