开发者

How to calculate the expression of a datatable

开发者 https://www.devze.com 2023-02-20 13:06 出处:网络
Current Code: foreach (Expressions e in expressionObj) { if ((e.Expression != null) && (e.ColumnName != null))

Current Code:

foreach (Expressions e in expressionObj)
{
   if ((e.Expression != null) && (e.ColumnName != null))
   {
      newtable1.Columns.Add(new DataColumn(e.ColumnName, typeof(decimal), e.Expression));
   }   
} 

I have an expression as ID+ID which is to be added as new column in the datatable as SUM-ID where ID=2, but the result got is 22 instea开发者_如何学Cd of 4.


Let's see:

DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("ID", typeof(decimal)));
dt.Columns.Add(new DataColumn("SUM-ID", typeof(decimal), "ID + ID"));
var row = dt.NewRow();
row["ID"] = 2;
dt.Rows.Add(row);
var val = dt.Rows[0]["SUM-ID"];

Result: val is 4 as expected.
Let's try something else:

DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("ID", typeof(string)));
dt.Columns.Add(new DataColumn("SUM-ID", typeof(decimal), "ID + ID"));
var row = dt.NewRow();
row["ID"] = "2";
dt.Rows.Add(row);
var val = dt.Rows[0]["SUM-ID"];

Result: val is 22

Conclusion: Your ID column is of type string but it needs to be a numeric type instead otherwise string concatenation is used.

Update: If you cannot (or don't want to) set the datatype of the column then you can use Convert inside the expression: 2 * Convert(ID, 'System.Int32')

0

精彩评论

暂无评论...
验证码 换一张
取 消