In my apps I will need to handle null value in a list.
Is there a way to do a sum in a foreach without using an if statement to check if an item is null in the list.
List<int?> numberList = new();
numberList.Add(32);
numberList.Add(21);
numberList.Add(null);
numberList.Add(11);
numberList.Add(89);
int? result = 0;
foreach (var item in numberList)
{
if (item != null)
{
result = item;
}
}
Console.WriteLine($"with if statement Value is : {result}");
CodePudding user response:
Is there a way to do a sum in a foreach without using an if statement to check if an item is null in the list.
Sure, you could use GetValueOrDefault:
foreach (var item in numberList)
{
result = item.GetValueOrDefault();
}
But then you lose the information if there was at least one item != null, because you'd treat a null item same as an item that is 0. Of course you can shorten code with LINQ:
int result = numberList.Sum(i => i.GetValueOrDefault());
CodePudding user response:
You can make use of LINQs Sum. Just use it in combination with the Coalescing Operator which allows to specify an explicit default value in case of null:
int sum = numberList.Sum(n => n ?? 0);
or more simple to use 0 as default:
int sum = numberList.Sum();
Note that you need to define usage of LINQ like
using System.Linq;
Without LINQ, you can also make use of the Coalescing Operator:
foreach (var item in numberList)
{
result = item ?? 0;
}
Note that this is from a runtime point of view exactly the same like you've showed in your example, it's just syntactic sugar.
