C#null和Any()检查的快捷方式 [英] A Shortcut for c# null and Any() checks

查看:610
本文介绍了C#null和Any()检查的快捷方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常在C#中我必须这样做

Often in C# I have to do this

if(x.Items!=null && x.Items.Any())
{ .... }

集合上有捷径吗?

推荐答案

在C#6中,您可以编写:

In C# 6, you'll be able to write:

if (x.Items?.Any() == true)

在此之前,您始终可以编写自己的扩展方法:

Before that, you could always write your own extensions method:

public static bool NotNullOrEmpty<T>(this IEnumerable<T> source)
{
    return source != null && source.Any();
}

然后只使用:

if (x.NotNullOrEmpty())

更改名称以适合您的口味,例如NullSafeAny可能更符合您的喜好-但是,即使x为null,我也一定会以有效的名称清楚地表明这一点.

Change the name to suit your tastes, e.g. NullSafeAny might be more to your liking - but I'd definitely make it clear in the name that it's a valid call even if x is null.

这篇关于C#null和Any()检查的快捷方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆