Make Linq return object or null
Is there a way to get the code below to return null if no objects are found?
var news = (from c in childs
where c.Name.ToLower().Contain开发者_StackOverflow社区s("folder")
select c).First();
You want to use FirstOrDefault() instead of First(). It will do exactly what you want.
You should call FirstOrDefault<T>
, which will return default(T)
if there are no elements.
default(T)
will be null
for reference and nullable types, 0
for numeric types (byte
, int
, double
, etc), and new T()
for structures (which cannot be null
)
精彩评论