0

I have couple of string variables that sometimes have text and other times have integers in them. I have a function Add() where I add all the variables when they are integers. Problem is how do I avoid any variable when they are string? Example:

string a = "2";
string b = "3";
string c = "10";
string d = "jk";
string e = "zu";
string f = "15";

public void Add(){
  int total = int.Parse(a) + int.Parse(b) + int.Parse(c) + int.Parse(d) + int.Parse(e) + int.Parse(f);
}

Obviously the above code will fail because d and e are string, what I am looking for is it should avoid adding d and e strings and the total should be 30. I can check if the string is an integer or a text but that would take forever if the script I am working on does not have strings as an array. What is the right and easy way to do this?

4
  • Instead of creating a slew of value variables, why not put the values into a collection and when adding, select only the numerical ones via Linq? Commented Jun 29, 2022 at 11:10
  • Yes that would be my way too. That I would add to a list/array and then loop through it. But unfortunately for this case lets say I have 25 strings that are not in any array/list, what can I possibly work then ? Commented Jun 29, 2022 at 11:13
  • @MickyD I know, but how do I avoid the addition of that string if it does not contain an integer? Commented Jun 29, 2022 at 11:14
  • Whoops my mistake Commented Jun 29, 2022 at 11:19

4 Answers 4

6

If you want to use spesific variables, you can code this use case like this

void Add()
{
  int aInt, bInt, cInt, dInt, eInt, fInt;
  int.TryParse(a, out aInt);
  int.TryParse(b, out bInt);
  int.TryParse(c, out cInt);
  int.TryParse(d, out dInt);
  int.TryParse(e, out eInt);
  int.TryParse(f, out fInt);
  int total = aInt + bInt + cInt + dInt + eInt + fInt;
}

If you want to use more extendible code, you should use collection

void Add()
{
  int total = 0;
  foreach (var c in myStrCollection)
  {
    int.TryParse(c, out int a);
    total += a;
  }
}

int.TryParse will try to convert the string to int. If it cannot convert, variable a will be 0 as default. 0 is ineffective element for addition. If this method is multiplication, you should change the method like this.

void Multiply()
{
  int total = 0;
  foreach (var c in myStrCollection)
  {
    bool s = int.TryParse(c, out int a);
    if(!s) a = 1;
    total *= a;
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

perfect explanation! Thank you :)
I am also looking for similar answer in php, if you have a solution for that too it would be great. Or I can post it as a different question.
I'm sorry I can't help about php. I have no experience on php
2

You can use this to check wether a string is parsable:

int intStr; 
bool intResultTryParse = int.TryParse(str, out intStr);  
if (intResultTryParse == true)  
{  
    Console.WriteLine(intStr);  
}  

And instead of parsing each string you can add them to a array and traverse it with a for each cycle.

So your code should look like this:

string a = "2";
string b = "3";
string c = "10";
string d = "jk";
string e = "zu";
string f = "15";

public int AddStrings(params string[] numbers)
{
    int numberContainer = 0;
    int sumContainer = 0;
    foreach (string number in numbers)
    {
        if (int.TryParse(number, out numberContainer))
        {
            sumContainer += numberContainer;
        }
    }
    return sumContainer;
}

public void Add()
{
    int total = AddStrings(a, b, c, d, e, f);
}

And of course you can keep adding strings to the AddStrings arguments because of the 'params' key word

Comments

1
var total = new []{a,b,c,d,e,f}
    .Select(x=>{
        int n; 
        var parsed = int.TryParse(x, out n);
        return new {n, parsed};
    })
    .Where(x=> x.parsed)
    .Select(x=> x.n)
    .Sum();

1 Comment

Image
Shorter: .Sum(x => { int n; int.TryParse(x, out n); return n; });
1

tried using LINQ

string[] k = { a, b, c, d, e, f };
var se = k.Where((a) => int.TryParse(a, out int l))
          .Select(x => int.Parse(x))
          .Aggregate((a, b) => a + b);
System.Console.WriteLine(se);

2 Comments

Why would you parse each string twice.... This is pessimization!
@Phil1970 yes I know I'm over killed, where() return type is bool, so the first TryParse includes only int type then using Select() I'm actually parsing it to int type then added up!. I'm just a beginner :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.