Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative to using a ternary operator in Lambda

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.

like image 797
jaekie Avatar asked Nov 30 '22 03:11

jaekie


2 Answers

PhoneNumber = x.PhoneNumbers.Select(pn => pn.PhoneNumber).FirstOrDefault() ?? "",
like image 167
Markus Jarderot Avatar answered Dec 05 '22 02:12

Markus Jarderot


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, "");
like image 34
Jon Skeet Avatar answered Dec 05 '22 03:12

Jon Skeet