【问题标题】:Expression on two integer type columns of datatable数据表的两个整数类型列上的表达式
【发布时间】:2012-04-12 07:23:33
【问题描述】:

我想知道如何在数据表中编写表达式来连接两个整数类型的列。因为当我尝试使用 '+' 时,它会添加两个整数。

提前致谢。

【问题讨论】:

  • 在使用“+”将整数转换为字符串之前...
  • 谢谢马可。但是你能告诉我如何将整数转换为字符串吗?因为要提供给数据列的表达式是字符串。所以如果你提供一个例子会很有帮助。
  • 你可以按照我的回答我希望:)

标签: c# datatable


【解决方案1】:

如果要设置结果列的表达式。试试这个。

DataTable table = new DataTable();

table.Columns.Add("OrderCount",typeof(int));

table.Columns.Add("OrderPrice",typeof(int));

table.Rows.Add(new object[] { 1, 1 });

table.Rows.Add(new object[] { 2, 3 });

table.Rows.Add(new object[] { 4, 5 });

table.Columns.Add("Result", typeof(string));

table.Columns["Result"].Expression = "Convert(OrderCount, 'System.String') + OrderPrice";

【讨论】:

    【解决方案2】:

    例子:

    int a = 1;
    int b = 2;
    
    var asInt = a + b; // asInt is now 3
    var asString = a.ToString() + b.ToString() // asString is now "12"
    var asStringAlt = String.Format("{0}{1}", a, b); // alternate method as suggested
    

    【讨论】:

    • 最好做一个 string.format,性能明智。所以var asString = string.Format("{0}{1}", a, b);。这种方式不需要不必要的字符串转换。
    • @Jan_V:更新以显示这两种方法。但不确定哪个性能更高。
    • 在很多书中他们告诉 string.Format() 是更好的(理论上)使用,因为性能和内存问题。但正如这篇文章中所建议的那样:stackoverflow.com/questions/296978/… 这可能并不重要。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-20
    • 1970-01-01
    • 1970-01-01
    • 2018-10-09
    • 2016-05-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多