For brevity\'s sake in my code, i\'d like to be able to do the following: having a collection, find the first element matching a lambda expression; if it exists, return the valu
I like this as an extension method:
public static U SelectMaybe(this T input, Func func)
{
if (input != null) return func(input);
else return default(U);
}
And usage:
var UpperValueOfAString = stuff.FirstOrDefault(s => s.Contains("bvi")).SelectMaybe(x => x.ToUpper());
var UpperValueOfAStringWannabe = stuff.FirstOrDefault(s => s.Contains("unknown token")).SelectMaybe(x => x.ToUpper());
This will chain return the default value (null
in this case, but as is correct for that type), or call the relevant function and return that.