tags:

views:

59

answers:

2

Hello,

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().Contains("folder")
select c).First();
+6  A: 

You want to use FirstOrDefault() instead of First(). It will do exactly what you want.

tvanfosson
Great, worked as a charm, thanks!
Zooking
+3  A: 

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)

SLaks
+1 for specifying what default(T) does.
cfern