简体   繁体   中英

how to check the if condition with string and integer

I want to get result of a value with if condition.

i have get some value in xml file.

now what I want is

if I have a variable "a" here i have assigned some values by using dataset. and i have another variable "b" is assigned value from xml file.

for example int a=25; string b=">10"

now I want to check the condition if condition with out ">" because the symbol present in b variable. I dont know how to check this condition can anybody explain me how to acheive this.

I tried like this but not working if(a+b)

You can have some function to remove non numeric characters:

public int Parse(string x)
{
  x = Regex.Replace(x, "[^0-9.]", "");
  int result = 0;
  int.TryParse(x , out result);
  return result; 
}

If its always a number with a symbol then:

symbol = b[0];
int bval = int.Parse(b.Substring(1))

And considering your comment for comparison you can do:

if((symbol=='>'&&a>b)||
   (symbol=='='&&a==b)||
   (symbol=='<'&&a<b)
  ){
       //do your magic here
   }

Of course you may need only one of < = > or you may need to have separate if conditions for each, what ever suits your needs, but I just wanted to give the idea.

You can use the DataTable.Compute -"trick" to evaulate such expressions:

int a = 25;
string b = ">10";
bool isTrue = (bool)new DataTable().Compute($"{a}{b}", null);  // true

What is supported you can read at the DataColumn.Expression remarks.


if the condition is 1!=10, how to use not equal in this code .this condition is not working what should i do.

As the documentation tells you that is not valid syntax, you have to use <> (look at operators). So a simple approach would be either to use <> in the first place or replace them:

b = b.Replace("!=", "<>");

First separate symbol from b:

string symbol = b[0].ToString();
string numberString = b.SubString(1);
int number = int.Parse(numberString);

Now use switch to get operation for symbol and compare:

bool result = false;
switch (symbol)
{
    case ">":
        if (a > number)
        {
            result = true;
        }
        break;
}

EDIT: Changed symbol declaration to avoid error: "cannot implicit convert type char to string"

I tried like this

if (b.Contains(">")) {
                                b = b.Replace(">", "");
                                if (a >Convert.ToInt32(b))
                                {
                                    Console.WriteLine("value is less");
                                }
                                else
                                {
                                    Console.WriteLine("value is Greater");
                                }
                            }

similarly all the symbols

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM