c# - Using Null coalescing operator in foreach with select expression -
foreach (var item in model.publishedsong.relatedsongs.select((value, i) => new { value, }) ?? enumerable.empty <dynamic>()) { } related songs may or may not null, there way use null coalescing operator here? still error message:
value cannot null
if relatedsongs null, calling select on throw nullreferenceexception, because null coalescing operator evaluated after left-hand side resolved. , since resolving left hand side results in exception, won't good.
if you're using c# 6.0, can use null propagation operator - ?. - call select if relatedsongs isn't null, , use null coalescing operator otherwise:
// return null if relatedsongs null, or call select otherwise. foreach (var item in model.publishedsong.relatedsongs?.select((value, i) => new { value, }) ?? enumerable.empty <dynamic>()) { } if you're using c# 5 or earlier, you'll have check null manually:
foreach (var item in model.publishedsong.relatedsongs != null ? model.publishedsong.relatedsongs.select((value, i) => new { value, }) : enumerable.empty <dynamic>()) { }
Comments
Post a Comment