首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在逗号上拆分,然后在C#中逐个求和数值。

在逗号上拆分,然后在C#中逐个求和数值。
EN

Stack Overflow用户
提问于 2014-01-24 00:12:09
回答 1查看 746关注 0票数 0

我一直试图解决这个问题3-4个小时,并在互联网上查看了许多例子。我可以用逗号分隔;但是,我不能一个一个地得到数字值并将它们相加。

代码语言:javascript
复制
var MyList = context.ProductAndPriceList();

我有字符串MyListMyList的值,如下所示

代码语言:javascript
复制
"Apple,5"

"Computer,7"

"Mouse,12"

结果必须是5+7+12=24

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-01-24 00:26:42

以伪(基于c#)的代码给出我的答案,因为我无法判断您使用的是哪种编程语言。下面的代码是未经测试的,但对于C# .Net来说应该是正确的,并概述了获得所需结果的逻辑。我希望您在尝试将拆分方法中的值添加到整数之前忘记将它们转换为整数。当您拆分一个字符串,即使您得到的结果看起来像5,它实际上仍然是"5“(字符串),如果这是合理的。

编辑:删除了我注意到的冗余代码。

代码语言:javascript
复制
//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);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21321997

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档