从两个不同的列表中添加两个值

时间:2014-08-21 07:14:34

标签: c#

当我的大脑彻底失败时,又是另一个时刻。

我正在尝试从两个单独的列表中添加(添加)两个值(小数)。老实说,我认为我遇到了价值类型的问题,但欢迎任何澄清。

public List<decimal> getTotalSellingPrice(int costSheetID) 
{
    List<decimal> totalSellingPrice = new List<decimal>();

    decimal bothMarkupAndToms = 0;
    foreach (var i in getMarkupPrice(costSheetID)) 
    {
      foreach (var m in getToms(costSheetID)) 
      {
          bothMarkupAndToms = i + m;                      
      }


      totalSellingPrice.Add(Math.Round(bothMarkupAndToms));   
    }

    return totalSellingPrice;
}

正如您在每个集合中看到的那样,我想在嵌套集合中添加另一个值。

因此,在每次传递时,它应该是“i + m”,然后添加到为UI准备的最终列表中。

非常感谢任何帮助!

3 个答案:

答案 0 :(得分:0)

如果要将项目(i + m)放入列表,请尝试以下操作:

public List<decimal> getTotalSellingPrice(int costSheetID) 
{
    List<decimal> totalSellingPrice = new List<decimal>();
    foreach (var i in getMarkupPrice(costSheetID))
    {
      foreach (var m in getToms(costSheetID))
      {
          totalSellingPrice.Add(Math.Round(i + m));
      }
    }
    return totalSellingPrice;
}

如果你想为每个i输出一个项目(我的所有m的总和),请尝试以下方法:

public List<decimal> getTotalSellingPrice(int costSheetID) 
{
    List<decimal> totalSellingPrice = new List<decimal>();
    decimal bothMarkupAndToms = 0;
    foreach (var i in getMarkupPrice(costSheetID)) 
    {
      bothMarkupAndToms = i;
      foreach (var m in getToms(costSheetID)) 
      {
          bothMarkupAndToms += m;                      
      }
      totalSellingPrice.Add(Math.Round(bothMarkupAndToms));   
    }
    return totalSellingPrice;
}

我希望有帮助

修改

我认为你试图从这两个列表中添加相应的元素,例如来自标记价格的第一个元素与来自toms的第一个元素,依此类推。根据这种情况,你想要像下面这样的东西:

public List<decimal> getTotalSellingPrice(int costSheetID) 
{
    List<decimal> totalSellingPrice = new List<decimal>();
    decimal bothMarkupAndToms = 0;
    List<decimal> markupPriceList = getMarkupPrice(costSheetID);
    List<decimal> tomsList = getToms(costSheetID);
    for(int i = 0 ; i < tomsList.size() ; i++)
    {
      totalSellingPrice.Add(Math.Round(markupPriceList[i] + tomsList[i]));   
    }
    return totalSellingPrice;
}

答案 1 :(得分:0)

这将为您提供getTotalSellingPrice()中每个值与getToms()的相应值的总和。如果两个列表各有4个值,则会在结果列表中为您提供4个值。你在做什么更像是排列。这是两个列表的正确添加。

public List<decimal> getTotalSellingPrice(int costSheetID)
{
    List<decimal> totalSellingPrice = new List<decimal>();
    List<object> toms = getToms(costSheetID);
    int j = 0,
        tomsCount = toms.Count;
    foreach (var i in getMarkupPrice(costSheetID))
    {
        if(j >= tomsCount )
            break;
        totalSellingPrice.Add(Math.Round(i + Convert.ToDecimal(toms[j])));
        j++;
    }

    return totalSellingPrice;
}

对于getMarkupPrice()中的每个值,上面的代码都会添加toms中的相应值(基于它用于跟踪j中当前值的索引toms )并将结果添加到totalSellingPrice列表中。 if内的其他foreach块会检查toms是否超出值。如果是,break;语句只退出执行foreach循环。

答案 2 :(得分:0)

问题在于你的2个foreach循环。您可以使用代码创建i * m值,而不是将im匹配,然后添加它们。对于每个i,您获得4 m,因此4 * 4将为您提供16个值。