Click here to Skip to main content
15,886,724 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
Hello,
I am in a dilemma, as I am not able to understand what is wrong n this piece of code.

C#
int m = 0;
while(m < soitemfinalprice.Length)
{
    Double soamt = 0;
    foreach (var soitem in so)
    {
        foreach (var soitemprice in soitem.SODetails)
        {
            soamt = soamt + soitemprice.SO_Item_Final_Price;
        }
        soitemfinalprice[m] = soamt;
        m++;
    }
}


Here, soitemfinalprice is an array, say of size 3. "so" is a List of class objects, and each "so" contains another List of objects.

Suppose "so" contains 3 items, say 'A', 'B', 'C'.
'A' has two 'SODetails', which has SO_Item_Final_Price values 100 and 200.
'B' has one 'SODetails', which has SO_Item_Final_Price value 100.
'C' has three 'SODetails', which has SO_Item_Final_Price values 50, 100 and 200.

My requirement is that, I need to get the following values:
soitemfinalprice[1] = 300, soitemfinalprice[2] = 100, soitemfinalprice[3] = 350.

What happens now is, I am getting values as:
soitemfinalprice[1] = 750, soitemfinalprice[2] = 750, soitemfinalprice[3] = 750.


What is wrong in this Loop code ?
Posted
Updated 25-Jul-14 6:13am
v2
Comments
joshrduncan2012 25-Jul-14 12:04pm    
Are you getting any errors or just incorrect output?
[no name] 25-Jul-14 12:11pm    
Run it through the debugger and you will probably find the problem.
PIEBALDconsult 25-Jul-14 12:15pm    
You might want to move Double soamt = 0;
inside the first foreach.

You've got your iterations wrong - your doing the same thing three times. Try this:
for (int m = 0; m < soitemfinalprice.Length; m++)
{
    int soamt = 0;
    foreach (var soitemprice in so[m].SODetails)
    {
        soamt = soamt + soitemprice.SO_Item_Final_Price;
    }
    soitemfinalprice[m] = soamt;
}


Although this will give you the answer in [0], [1] and [2], not 1,2.3
 
Share this answer
 
You are not resetting the value of soamt. The following code will fix it. Cheers :)

C#
int m = 0;
while(m < soitemfinalprice.Length)
{
    Double soamt;
    foreach (var soitem in so)
    {
        soamt = 0; //Reset soamt to 0
        foreach (var soitemprice in soitem.SODetails)
        {
            soamt = soamt + soitemprice.SO_Item_Final_Price;
        }
        soitemfinalprice[m] = soamt;
        m++;
    }
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900