Search code examples
c#linqnullnull-check

Deep null check inside linq expression, is there a better way?


Unless it's in the Linq expression I could use the operator "?.". But since I can't use it in Linq, it's bad code writing. How can I do a deep null check?

_collection.Select(x=> new CollectionModel
{
Title = x.CollectionValues != null &&
        x.CollectionValues.Any(x => x.Amount == amount) &&
        x.CollectionValues.First(x => x.Amount == amount).TranslationTitle != null && 
        x.CollectionValues.First(x => x.Amount == amount).TranslationTitle.TranslationValues != null &&
        x.CollectionValues.First(x => x.Amount == amount).TranslationTitle.TranslationValues.Any(x => x.LanguageId == languageId) ?
        x.CollectionValues.First(x => x.Amount == amount).TranslationTitle.TranslationValues.FirstOrDefault(x => x.LanguageId == languageId).Value 
        : ""
}
)

Solution

  • Try to do not do any null checks in LINQ to Entities query. EF should handle nulls automatically:

    _collection.Select(x=> new CollectionModel
        {
            Title = x.CollectionValues!.FirstOrDefault(x => x.Amount == amount)!
                .TranslationTitle.TranslationValues!
                .FirstOrDefault(x => x.LanguageId == languageId)!
                .Value ?? ""
        }
    );