Click here to Skip to main content
15,064,140 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
int size=0;

foreach (char c in s)             
{                 
    int intc = Convert.ToInt32(c.ToString());                 
    Size = Size + intc;             
}


What I have tried:

I have tried
size = s.ToList().ForEach(x => { Convert.ToInt32(x) + size ; });
which is not working and giving error.
Posted
Updated 6-Mar-17 20:52pm
v2

int size = 0;
      string s = "12345";
      size= s.Sum(k => Convert.ToInt32(k.ToString()));


refer LINQ Sum[^]

Correction to your code

int size = 0;
       string s = "12345";
       s.ToList().ForEach(x => size += Convert.ToInt32(x.ToString()));
       // ForEach will not return any data, its Void
        // now size will have 15
   
v2
Here are a couple of variants on Karthik's solution:
C#
string s = "12345";
int size = s.Sum(x => x - '0');
C#
string s = "12345";
int size = s.Sum(x => CharUnicodeInfo.GetDecimalDigitValue(x));
Both remove all the boxing operations... ;)
   
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900