Linq查询包含空值

时间:2013-10-28 16:06:46

标签: c# linq

var records = from entity in q1.question_papers
              select new
              {
                  QuestionPaperID = entity.QUESTION_PAPER_ID,
                  SubjectID = entity.SUBJECT_ID,       
                  PreviousAttempts = SubIdAtt.Where(c => c.SUBID == entity.SUBJECT_ID)
                                             .Select(c => c.ATT)   
                                             .FirstOrDefault(),
              };

上面是我的linq查询,在PreviousAttempts字段中,如果不满足where,我会得到null值。因此,如果它包含null,我想要更改此0,如果它不包含非null值,则返回原始值。

我怎样才能实现这一目标,因为我无法为每条记录更改PreviousAttempts

2 个答案:

答案 0 :(得分:9)

您可以在此处使用null-coalescing运算符,例如

PreviousAttempts = SubIdAtt.Where(c => c.SUBID == entity.SUBJECT_ID)
                           .Select(c => c.ATT)
                           .FirstOrDefault() ?? 0;

或者,如果你想保留所有LINQified,请使用DefaultIfEmpty方法,例如

PreviousAttempts = SubIdAtt.Where(c => c.SUBID == entity.SUBJECT_ID)
                           .Select(c => c.ATT)
                           .DefaultIfEmpty(0)
                           .FirstOrDefault();

答案 1 :(得分:6)

您可以使用合并运算符。 ??

           var records = from entity in q1.question_papers
                           select new
                           {
                               QuestionPaperID = entity.QUESTION_PAPER_ID,
                               SubjectID = entity.SUBJECT_ID,

                               PreviousAttempts = SubIdAtt.Where(c => c.SUBID == entity.SUBJECT_ID).Select(c => c.ATT).FirstOrDefault() ?? 0
                           };