简体   繁体   中英

How to check list object is not null before using ForEach lambda expression

I want to know how can check list object is not null before using ForEach loop. Below is example code which I am trying:

List<string> strList   ;
strList.ForEach (x => Console.WriteLine(x)) ;

I looking for a solution in terms of lambda expression and do not want to use if statement.

You can write an extension method for List<> , which will check for null and otherwise it will call ForEach on its this parameter. Call it ForEachWithNullCheck or something like this and you will be fine.

public static void ForEachWithNullCheck<T>(this List<T> list, Action<T> action)
{
  if (list == null)
  {
    // silently do nothing...
  }
  else
  {
    list.ForEach(action); 
  }
}

Usage example:

List<string> strList;
strList.ForEachWithNullCheck(x => Console.WriteLine(x));

You might have already got a better solution. Just wanted to show how I did it.

List<string> strList   ;
strList.ForEach (x => string.IsNullOrEmpty(x)?Console.WriteLine("Null detected"): Console.WriteLine(x)) ;

In my scenario I am summing up a value in a foreach as shown below.

double total = 0;
List<Payment> payments;
payments.ForEach(s => total += (s==null)?0:s.PaymentValue);

The most correct/idiomatic solution (if you cannot avoid having a null collection to begin with ) is to use an if :

if(list != null)
    foreach(var str in list)
        Console.WriteLine(str);

Putting the if into a lambda isn't going to make anything any easier. In fact, it'll only create more work.

Of course if you really hate using an if you can avoid it, not that it'll really help you much:

foreach(var str in list??new List<string>())
    Console.WriteLine(str);

foreach(var str in list == null ? new List<string>() : list)
    Console.WriteLine(str);

You could emulate the more functional style Maybe concept with a method that invokes an action if the object isn't null , not that this is really any easier than a null check when dealing with actions instead of functions:

public static void Maybe<T>(this T obj, Action<T> action)
{
    if (obj != null)
        action(obj);
}

strList.Maybe(list =>
    foreach(var str in list)
        Console.WriteLine(str));

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