Sum of absolute numbers in function

Viewed 159

I try this:

public static int sum(List<int> list)
{
        int sum = 0;

        foreach (var item in list)
        {
            sum = item + sum;
        }

        return sum;
}

public static int sumAbsolute(List<int> list)
{
        foreach (var item in list)
        {
            Math.Abs(item);
        }          

        return sum(list); 
}

and the in the main function:

static void Main(string[] args)
{          
        var list = new List<int>() {
            -1,-2,-3
        }; 

        Console.WriteLine(sumAbsolute(list));
        Console.ReadKey();
}

But the output is -6 and not 6.

So why doesn't my code work?

1 Answers

In short: because Math.Abs(item) returns an int that you dont use:

If you really want to replace all ints in the list, you could do:

for(int i = 0; i < list.Length; i++)
{
    list[i] = Math.Abs(list[i]);
} 

or with LINQ, this also doesn't need to modify the list:

public static int SumAbsolute(IEnumerable<int> list)
{
    return list.Select(Math.Abs).Sum();
}
Related