Safely dereferencing FirstOrDefault call in Linq c#
Posted
by
samy
on Stack Overflow
See other posts from Stack Overflow
or by samy
Published on 2012-06-27T09:01:30Z
Indexed on
2012/06/27
9:15 UTC
Read the original article
Hit count: 200
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?
© Stack Overflow or respective owner