3
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,我想更改此 0 而不是包含 null,如果它不包含非 null 值,则恢复原始值。

由于我无法更改PreviousAttempts每条记录,我该如何实现这一目标?

4

2 回答 2

9

您可以在此处使用空合并运算符,例如

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();
于 2013-10-28T16:09:38.577 回答
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
                           };
于 2013-10-28T16:10:30.820 回答