foreach里面for循环有什么问题? [英] What is wrong with foreach inside for loop ?

查看:66
本文介绍了foreach里面for循环有什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,

我处于两难境地,因为我无法理解这段代码有什么问题。



Hello,
I am in a dilemma, as I am not able to understand what is wrong n this piece of code.

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++;
    }
}





这里,soitemfinalprice是一个数组,比如3号。所以是一个类对象列表,每个所以包含另一个对象列表。



假设so包含3个项目,比如'A',' B','C'。

'A'有两个'SODetails',其SO_Item_Final_Price值为100和200.

'B'有一个'SODetails',其SO_Item_Final_Price值为100。 />
'C'有三个'SODetails',其SO_Item_Final_Price值为50,100和200.



我的要求是,我需要得到以下值:

soitemfinalprice [1] = 300,soitemfinalprice [2] = 100,soitemfinalprice [3] = 350.



什么现在发生的是,我得到的值是:

soitemfinalprice [1] = 750,soitemfinalprice [2] = 750,soitemfinalprice [3] = 750.





这个循环代码出了什么问题?



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 ?

推荐答案

你的迭代错了 - 你这样做了事情三次。试试这个:

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





虽然这会给你[0],[1]和[2]中的答案,而不是1 ,2.3



Although this will give you the answer in [0], [1] and [2], not 1,2.3


您没有重置 soamt 的值。以下代码将修复它。干杯:)



You are not resetting the value of soamt. The following code will fix it. Cheers :)

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++;
    }
}


这篇关于foreach里面for循环有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆