简体   繁体   English

在使用ForEach Lambda表达式之前如何检查列表对象不为null

[英]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. 我想知道在使用ForEach循环之前如何检查列表对象是否为null。 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. 我正在寻找一种关于lambda表达式的解决方案,并且不想使用if语句。

You can write an extension method for List<> , which will check for null and otherwise it will call ForEach on its this parameter. 您可以为List<>编写扩展方法,该方法将检查是否为null,否则将在其this参数上调用ForEach Call it ForEachWithNullCheck or something like this and you will be fine. 将其命名为ForEachWithNullCheck或类似的名称,您会满意的。

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. 在我的场景中,我正在foreach中汇总一个值,如下所示。

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 : 最正确/惯用的解决方案(如果不能避免以开头的null集合 )是使用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. if放入lambda不会使任何事情变得容易。 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: 当然,如果你真的很讨厌使用if避免它,而不是它会真正帮助你多少:

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: 您可以使用一种方法来模拟更具功能性的Maybe概念,该方法可以在对象不是null调用操作,这比在处理操作而不是函数时进行null检查要容易得多:

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));

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

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