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(),
              };

Above is my linq query where in PreviousAttempts field I get null value if doesn't satisfy where. So instead of containing null I want to change this 0 if it contains null and restore original value if it doesn't contain non null value.

How can I achieve this since I am not able to change PreviousAttempts through for each of record?

2 Answers 2

9

You can use the null-coalescing operator here e.g.

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

Or alternatively, if you want to keep it all LINQified use the DefaultIfEmpty method e.g.

PreviousAttempts = SubIdAtt.Where(c => c.SUBID == entity.SUBJECT_ID)
                           .Select(c => c.ATT)
                           .DefaultIfEmpty(0)
                           .FirstOrDefault();
Sign up to request clarification or add additional context in comments.

Comments

6

You could use the coalescing operator. ??

           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
                           };

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.