我一直试图解决这个问题3-4个小时,并在互联网上查看了许多例子。我可以用逗号分隔;但是,我不能一个一个地得到数字值并将它们相加。
var MyList = context.ProductAndPriceList();我有字符串MyList和MyList的值,如下所示
"Apple,5"
"Computer,7"
"Mouse,12"结果必须是5+7+12=24
发布于 2014-01-24 00:26:42
以伪(基于c#)的代码给出我的答案,因为我无法判断您使用的是哪种编程语言。下面的代码是未经测试的,但对于C# .Net来说应该是正确的,并概述了获得所需结果的逻辑。我希望您在尝试将拆分方法中的值添加到整数之前忘记将它们转换为整数。当您拆分一个字符串,即使您得到的结果看起来像5,它实际上仍然是"5“(字符串),如果这是合理的。
编辑:删除了我注意到的冗余代码。
//Your list
var MyList = context.ProductAndPriceList();
//My variables
int total = 0;
foreach(string val in MyList){
//Split your string to get the number (still as a String)
string str_number = val.split(',')[1];
//Convert the number string into an int variable
int int_number = int.Parse(str_number);
//Add this value to the total
total += int_number;
}
//Display the total count in the console to check its working.
console.writeLine(total);https://stackoverflow.com/questions/21321997
复制相似问题