简体   繁体   English

如何避免在 foreach IList 之前检查 null

[英]How to avoid null checking before foreach IList

I have the following code:我有以下代码:

IList<object> testList = null;

... 

if (testList != null) // <- how to get rid of this check?
{
   foreach (var item in testList)
   {
       //Do stuff.
   }
}

Is there a way to avoid the if before the foreach ?有没有办法避免if之前的foreach I saw a few solutions but when using List , is there any solution when using IList ?我看到了一些解决方案,但是在使用List时,使用IList时有什么解决方案吗?

Well, you can try ??嗯,你可以试试?? operator:操作员:

testList ?? Enumerable.Empty<object>()

we get either testList itself or an empty IEnumerable<object> :我们得到testList本身或空的IEnumerable<object>

IList<object> testList = null;

...

// Or ?? new object[0] - whatever empty collection implementing IEnumerable<object>
foreach (var item in testList ?? Enumerable.Empty<object>())
{
    //Do stuff.
}

Try this尝试这个

IList<object> items = null;
items?.ForEach(item =>
{
  // ...
});

I stole the following extension method from a Project:我从一个项目中窃取了以下扩展方法:

public static IEnumerable<T> NotNull<T>(this IEnumerable<T> list)
{
    return list ?? Enumerable.Empty<T>();
}

Then use conveniently like this然后像这样方便地使用

foreach (var item in myList.NotNull())
{

}

you can create extention method like this:您可以像这样创建扩展方法:

public static IList<T> OrEmptyIfNull<T>(this IList<T> source)
 {
       return source ?? Enumerable.Empty<T>().ToList();
 }

Then you can write:然后你可以写:

 foreach (var item in testList.OrEmptyIfNull())
    {
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM