Safely dereferencing FirstOrDefault call in Linq c#
- by samy
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 value of a property or function. If it doesn't exist, return null.
var stuff = {"I", "am", "many", "strings", "obviously"};
var UpperValueOfAString = stuff.FirstOrDefault(s => s.contains("bvi")).ToUpper(); // would return "OBVIOUSLY"
var UpperValueOfAStringWannabe = stuff.FirstOrDefault(s => s.contains("unknown token")).ToUpper(); // would return null
Is it possible with some linq-syntax-fu or do i have to check explicitly for the return value before proceeding?