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}");
>Solution :
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());