Refactoring LINQ query to accommodate null values / missing properties -
i have string array has variable number of properties need parse. i’m using linq parse data can’t thinking there’s more efficient/elegant way achieve duplicate linq have done. there inherent way account null values (because property may or may not present in array) doing here:
mycollection.stringarray .where(e => e.name == "aproperty") != null ? mycollection.stringarray.where(e => e.name == "aproperty") firstordefault().value : string.empty;
ultimately, want pull value property if exists in collection, else need empty string (or null). however, don’t want exceptions thrown.
if want prevent exception if you're trying access empty sequence, can use defaultifempty
:
string value = mycollection.stringarray .where(e => e.name == "aproperty") .select(e => e.value) .defaultifempty(string.empty) .first();
it's important select value
property first safe if doesn't exist. defaultifempty
can use first
instead of firstordefault
.
Comments
Post a Comment