user9570515
user9570515

Reputation:

Adding the calculated sum of a list to another list

I have a list of int .. How can i sum all the numbers in the list and get the result ?

List<int> FineListy = new List<int>();

Upvotes: 0

Views: 412

Answers (3)

Aousaf Rashid
Aousaf Rashid

Reputation: 5738

If you have a list of int, why not use sum function??

int sum = FineListy.Sum();

This will add up all the numbers and give you the expected result.Now i see you do an If check to see if the number is not 0.So,create a new list then and pass the numbers to the list only if it's greater than 0

List<int> NewList = new List<int>;

foreach (var number in IntegerList)
{
    if (number > 0)
    {
        NewList.Add(number);
    }
}

Finally get the sum total :

 int sum = NewList.Sum();

Or one-line LINQ solution :

 var result = fineList.Where(a => a > 0).Sum();
 NewList.Add(result );

Upvotes: 1

ProgrammingLlama
ProgrammingLlama

Reputation: 38785

Your code has a number of issues.

List<int> FineListy = new List<int>();
for (int i = 0; i < fineList.Count(); i++)
{
    if (fineList[i] > 0)
    {
        FineListy.Add((fineList[i] += fineList[i]));              
    }
}

Firstly: C# naming conventions are such that local variables should start with lowercase letters and be camelCased. I recommend naming your variables totalsList and fineList respectively. For the sake of simplicity, I will use your current naming conventions below.

Next, you're doing FineListy.Add(fineList[i] += fineList[i]); which is the same as:

fineList[i] = fineList[i] * 2;
FineListy.Add(fineList[i]);

And you're doing it in a loop, so you will simply get a list of all items multiplied by 2.

Now you could fix this like so:

int total = 0;
for (int i = 0; i < fineList.Count; ++i)
{
    if (fineList[i] > 0)
    {
        total += fineList[i];
    }
}
FineListy.Add(total);

But you can use LINQ to do the same in a single line (I've split it across multiple lines to make it easier to read):

var total = fineList
                .Where(v => v > 0)
                .Sum();
FineListy.Add(total);

Or simply:

FineListy.Add(fineList.Where(v => v > 0).Sum());

Upvotes: 2

user9569533
user9569533

Reputation:

Yes, it doubles, because that's what you do here :

FineListy.Add((fineList[i] += fineList[i])); 

You say : "Add me fineList[i] + fineList[i] to my resulting collection FineListy" So you got all elements doubled.

If you want to add values you don't need list just a variable to store it and LINQ .Sum() method

P.S. I mean either one of these two (as others suggested):

FineListy.Add(fineList.Sum());

Or

int sum = fineList.Sum();

Upvotes: -1

Related Questions