简体   繁体   中英

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 ? I saw a few solutions but when using List , is there any solution when using IList ?

Well, you can try ?? operator:

testList ?? Enumerable.Empty<object>()

we get either testList itself or an empty 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())
    {
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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