Currently.. my code looks like this.
PhoneNumber = x.PhoneNumbers.FirstOrDefault() != null ? x.PhoneNumbers.FirstOrDefault().PhoneNumber : string.Empty,
PhoneNumbers is an ICollection<PhoneNumber>
This is also in a .Select()
, so I can't really create a variable for it outside.
Resharper is complaining that x.PhoneNumbers.FirstOrDefault()
could be null, and to be honest, not sold on the idea that I gotta do a FirstOrDefault twice.
Any other ideas, I'm thinking there could be another Lambda method I can do something similar.
PhoneNumber = x.PhoneNumbers.Select(pn => pn.PhoneNumber).FirstOrDefault() ?? "",
First option, like Markus's:
PhoneNumber = x.PhoneNumbers.Select(x => x.PhoneNumber)
.FirstOrDefault() ?? "";
Another alternative:
PhoneNumber = x.PhoneNumbers.Select(x => x.PhoneNumber)
.DefaultIfEmpty("")
.First();
Or if you find yourself doing this a lot, you could write your own method to combine the two:
public static TElement ProjectedFirstOrDefault<TSource, TElement>
(this IEnumerable<TSource> source,
Func<TSource, TElement> selector,
TElement defaultValue) where TElement : class
{
var firstElement = source.FirstOrDefault();
return firstElement == null ? defaultValue : selector(firstElement);
}
Then:
PhoneNumber = x.PhoneNumbers.ProjectedFirstOrDefault(x => x.PhoneNumber, "");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With