如何用字符串和整数检查if条件
how to check the if condition with string and integer
我想通过 if 条件获取一个值的结果。
我在 xml 文件中得到了一些值。
现在我想要的是
如果我有一个变量 "a",我已经使用数据集分配了一些值。
我还有另一个变量 "b" 从 xml 文件中赋值。
例如
int = 25;
字符串 b=">10"
现在我想检查没有“>”的条件,因为 b 变量中存在符号。我不知道如何检查这个条件谁能解释我如何实现这个。
我这样试过但没有用
如果(a+b)
您可以使用一些函数来删除非数字字符:
public int Parse(string x)
{
x = Regex.Replace(x, "[^0-9.]", "");
int result = 0;
int.TryParse(x , out result);
return result;
}
如果它总是一个带符号的数字,那么:
symbol = b[0];
int bval = int.Parse(b.Substring(1))
考虑到您的比较评论,您可以这样做:
if((symbol=='>'&&a>b)||
(symbol=='='&&a==b)||
(symbol=='<'&&a<b)
){
//do your magic here
}
当然,您可能只需要 <=> 之一,或者您可能需要为每个条件设置单独的 if 条件,只要适合您的需求即可,但我只是想表达一下想法。
您可以使用DataTable.Compute
-"trick"来计算这样的表达式:
int a = 25;
string b = ">10";
bool isTrue = (bool)new DataTable().Compute($"{a}{b}", null); // true
您可以在 DataColumn.Expression
备注中阅读支持的内容。
if the condition is 1!=10, how to use not equal in this code .this
condition is not working what should i do.
由于 documentation 告诉您这是无效语法,您必须使用 <>(查看运算符)。因此,一个简单的方法是首先使用 <> 或替换它们:
b = b.Replace("!=", "<>");
第一个与 b 分开的符号:
string symbol = b[0].ToString();
string numberString = b.SubString(1);
int number = int.Parse(numberString);
现在使用 switch 获取符号操作并比较:
bool result = false;
switch (symbol)
{
case ">":
if (a > number)
{
result = true;
}
break;
}
编辑:更改 symbol
声明以避免错误:"cannot implicit convert type char to string"
我这样试过
if (b.Contains(">")) {
b = b.Replace(">", "");
if (a >Convert.ToInt32(b))
{
Console.WriteLine("value is less");
}
else
{
Console.WriteLine("value is Greater");
}
}
同样所有符号
我想通过 if 条件获取一个值的结果。
我在 xml 文件中得到了一些值。
现在我想要的是
如果我有一个变量 "a",我已经使用数据集分配了一些值。 我还有另一个变量 "b" 从 xml 文件中赋值。
例如 int = 25; 字符串 b=">10"
现在我想检查没有“>”的条件,因为 b 变量中存在符号。我不知道如何检查这个条件谁能解释我如何实现这个。
我这样试过但没有用 如果(a+b)
您可以使用一些函数来删除非数字字符:
public int Parse(string x)
{
x = Regex.Replace(x, "[^0-9.]", "");
int result = 0;
int.TryParse(x , out result);
return result;
}
如果它总是一个带符号的数字,那么:
symbol = b[0];
int bval = int.Parse(b.Substring(1))
考虑到您的比较评论,您可以这样做:
if((symbol=='>'&&a>b)||
(symbol=='='&&a==b)||
(symbol=='<'&&a<b)
){
//do your magic here
}
当然,您可能只需要 <=> 之一,或者您可能需要为每个条件设置单独的 if 条件,只要适合您的需求即可,但我只是想表达一下想法。
您可以使用DataTable.Compute
-"trick"来计算这样的表达式:
int a = 25;
string b = ">10";
bool isTrue = (bool)new DataTable().Compute($"{a}{b}", null); // true
您可以在 DataColumn.Expression
备注中阅读支持的内容。
if the condition is 1!=10, how to use not equal in this code .this condition is not working what should i do.
由于 documentation 告诉您这是无效语法,您必须使用 <>(查看运算符)。因此,一个简单的方法是首先使用 <> 或替换它们:
b = b.Replace("!=", "<>");
第一个与 b 分开的符号:
string symbol = b[0].ToString();
string numberString = b.SubString(1);
int number = int.Parse(numberString);
现在使用 switch 获取符号操作并比较:
bool result = false;
switch (symbol)
{
case ">":
if (a > number)
{
result = true;
}
break;
}
编辑:更改 symbol
声明以避免错误:"cannot implicit convert type char to string"
我这样试过
if (b.Contains(">")) {
b = b.Replace(">", "");
if (a >Convert.ToInt32(b))
{
Console.WriteLine("value is less");
}
else
{
Console.WriteLine("value is Greater");
}
}
同样所有符号