字符串上的和数

时间:2014-06-17 11:47:52

标签: c# string

使用C# 我有一串与','分开的数字,如...

“3,2,2,1,2,1,2”

我想总结字符串上的数字,怎么做...以简单的方式? 3 + 2 + 2 + 1 + 2 + 1 + 2 = 13

任何想法?

这里是我的代码...我的字符串是SupplierAnswer,但它不起作用

Grad是Int SupplierAnswer是字符串

      StringBuilder strb = new StringBuilder();

        if (_Project.ProjectRequirements != null)
        {
            foreach (Requiernments Req in _Project.ProjectRequirements)
            {
                strb.Append(Req.SupplierAnswer + ",");
                this.AddRequirement(Req);
            }

            this.SupplierAnswers = strb.ToString();

           this.Grad = SupplierAnswers.Split(',').Select(c => int.Parse(c)).Sum(); 



            this.SupplierAnswers =   this.SupplierAnswers.Remove(this.SupplierAnswers.Length - 1);
        }

1 个答案:

答案 0 :(得分:7)

使用Split将字符串分隔成多个字符串,然后使用Int32.Parse将这些字符串转换为整数。然后,将Sum方法用于此整数列表。

Linq很简单!

String example = "3,2,2,1,2,1,2";
Int32 sum = example.Split(new char[] { ',' })   // get the "list" of strings
                   .Select(n => Int32.Parse(n)) // get the "list" of integers
                   .Sum();                      // get the sum