假设我们要完成下面的逻辑:
If ColumnA - ColumnB > 100, ColumnC = “Yes“, else ColumnC = “No“
则创建DataTable的代码如下:
// Create the DataTable
DataTable dt = new DataTable("Expressions");
// Create ColumnA and ColumnB
DataColumn columnA = new DataColumn("columnA", typeof(int));
DataColumn columnB = new DataColumn("columnB", typeof(int));
// Create ColumnC
DataColumn columnC = new DataColumn("columnC", typeof(string),
"IIF(columnA - columnB > 100,'Yes','No')");
// Add Columns to DataTable
dt.Columns.AddRange(new DataColumn[] { columnA, columnB, columnC });
// Add a Couple of Rows Supplying ColumnA and ColumnB Data
dt.Rows.Add(new object[] { 200, 80 });
dt.Rows.Add(new object[] { 100, 10 });
DataTable dt = new DataTable("Expressions");
// Create ColumnA and ColumnB
DataColumn columnA = new DataColumn("columnA", typeof(int));
DataColumn columnB = new DataColumn("columnB", typeof(int));
// Create ColumnC
DataColumn columnC = new DataColumn("columnC", typeof(string),
"IIF(columnA - columnB > 100,'Yes','No')");
// Add Columns to DataTable
dt.Columns.AddRange(new DataColumn[] { columnA, columnB, columnC });
// Add a Couple of Rows Supplying ColumnA and ColumnB Data
dt.Rows.Add(new object[] { 200, 80 });
dt.Rows.Add(new object[] { 100, 10 });
大家可以看到,这里面用到了IIF这样的函数,它的语法如下:
IIF(expr, truepart, falsepart)
expr -- 表达式
truepart -- 表达式成立时列的值
falsepart -- 表达式不成立时列的值
原文: http://davidhayden.com/blog/dave/archive/2006/07/09/DataColumnExpressions.aspx