Home > OS >  Check null for all participants in a union LINQ
Check null for all participants in a union LINQ

Time:09-10

As an example for the following scenario, how can I check whether quizType1Attempt and/or quizType2Attempt is null (without checking before these statements)?

var resultRecord = studentDomain.quizType1Attempts.Select(quizType1Attempt => new resultRecord {
    Id = quizType1Attempt.Id,
    Subject = quizType1Attempt.Subject,
    ...
}).Union(studentDomain.quizType2Attempts.Select(quizType2Attempt => new resultRecord {
    Id = quizType2Attempt.Id,
    Subject = quizType2Attempt.Subject
    ...
})).ToList();

CodePudding user response:

Just add null-coalescing operator (?) after nullable object.

var resultRecord = studentDomain.quizType1Attempts?.Select(quizType1Attempt => new resultRecord
        {
            Id = quizType1Attempt.Id,
            Subject = quizType1Attempt.Subject
        }) ?? new List<resultRecord>().Union(studentDomain.quizType2Attempts?.Select(quizType2Attempt => new resultRecord
        {
            Id = quizType2Attempt.Id,
            Subject = quizType2Attempt.Subject
        }) ?? new List<resultRecord>()).ToList();

CodePudding user response:

You can add a Where() predicate to filter your items in the list.

var resultRecord = studentDomain.quizType1Attempts.Where(q1 => q1 != null).Select(quizType1Attempt => new resultRecord {
    Id = quizType1Attempt.Id,
    Subject = quizType1Attempt.Subject,
    ...
}).Union(studentDomain.quizType2Attempts.Where(q2 => q2 != null).Select(quizType2Attempt => new resultRecord {
    Id = quizType2Attempt.Id,
    Subject = quizType2Attempt.Subject
    ...
})).ToList();
  • Related