建立運算式資料行Creating Expression Columns

您可以定義資料行的運算式,使其包含從相同資料列的其他資料行值,或從資料表的多重資料列的資料行值來計算所得的值。You can define an expression for a column, enabling it to contain a value calculated from other column values in the same row or from the column values of multiple rows in the table. 若要定義要評估的運算式,請使用目標資料行的 Expression 屬性,並使用 ColumnName 屬性來參照運算式中的其他資料行。To define the expression to be evaluated, use the Expression property of the target column, and use the ColumnName property to refer to other columns in the expression. 運算式資料行的 DataType 必須適用於運算式傳回的值。The DataType for the expression column must be appropriate for the value that the expression returns.

下表列出數個資料表的運算式資料行可能使用的方法。The following table lists several possible uses for expression columns in a table.

運算式型別Expression type 範例Example
邏輯比對Comparison "Total > = 500""Total >= 500"
計算Computation "UnitPrice * Quantity""UnitPrice * Quantity"
彙總Aggregation Sum(Price)Sum(Price)

您可以在現有的DataColumn物件上設定DataColumn Expression屬性,也可以將屬性包含為傳遞給此函式的第三個引數,如下列範例所示。You can set the Expression property on an existing DataColumn object, or you can include the property as the third argument passed to the DataColumn constructor, as shown in the following example.

workTable.Columns.Add("Total",Type.GetType("System.Double"))  
workTable.Columns.Add("SalesTax", Type.GetType("System.Double"), _  
  "Total * 0.086")  
workTable.Columns.Add("Total", typeof(Double));  
workTable.Columns.Add("SalesTax", typeof(Double), "Total * 0.086");  

運算式可參考其他運算式資料行;但循環參考 (兩個運算式互相參考) 將產生例外狀況。Expressions can reference other expression columns; however, a circular reference, in which two expressions reference each other, will generate an exception. 如需撰寫運算式的相關規則, Expression請參閱DataColumn類別的屬性。For rules about writing expressions, see the Expression property of the DataColumn class.

另請參閱See also