Reputation: 3364
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.
Upvotes: 0
Views: 4914
Reputation: 10460
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));
Upvotes: 2
Reputation: 89
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);
Upvotes: -1
Reputation: 203802
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));
Upvotes: -1