开发者

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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜