Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# – Sum List having some null

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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());
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading