简体   繁体   English

使用 DataTable.Compute() 方法比较 C# Visual Studio 中的两个变量

[英]Compare two variables in C# Visual Studio using DataTable.Compute() method

DataTable dt = new DataTable();
string output = (dt.Compute("3 > 2", String.Empty)).ToString();
MessageBox.Show("Output is " + output);

if I compare 3 > 2, it gives me True but I want to achieve similar functionality如果我比较 3 > 2,它给了我 True 但我想实现类似的功能

using variables such as:使用变量,例如:

string output = (dt.Compute("a > b", String.Empty)).ToString();字符串 output = (dt.Compute("a > b", String.Empty)).ToString();

how can I add my variables to the table to achieve this?如何将变量添加到表中以实现此目的?

Compute needs a string expression to work, you can provide the expression with interpolating the values from your variables as in Compute 需要一个字符串表达式才能工作,您可以为表达式提供插值变量的值,如

int a = 3;
int b = 2;
string output = (dt.Compute($"{a} > {b}", String.Empty)).ToString();

However, as @JohnG pointed in a comment below, a question needs to be asked here.但是,正如@JohnG在下面的评论中指出的那样,这里需要提出一个问题。 Why do you need this?你为什么需要这个? You can get the same result with probably a better performance using simple lines of code like您可以使用简单的代码行获得相同的结果,但性能可能更好

string output = "false";
if(a > b)
    output = "true";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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