在某些情况下DataTable是非常有用的。DataTable的操作基本就会有相关的计算、统计、聚合、筛选等。DataColumn中提供了Expression属性。他的定义如下:

获取或设置表达式,用于筛选行、计算列中的值或创建聚合列。

Expression属性的一个用途是创建计算出的列。

例如,若要计算税值,就要将单价乘以特定地区的税率。 由于各地税率不同,不可能将单一税率放在一个列中;于是便用 Expression 属性来计算这个值,如下面这一部分中的 Visual Basic 代码所示:

DataSet1.Tables("Products").Columns("tax").Expression = "UnitPrice * 0.086"

第二个用途是创建聚合列。 类似于计算出的值,聚合基于 DataTable 中的整个行集执行操作。一个简单的示例就是计算该集中返回的行数。 这便是您将用来计算特定销售人员所完成的交易数的方法,如下面的 Visual Basic 代码所示:

 DataSet1.Tables("Orders").Columns("OrderCount").Expression = "Count(OrderID)"

由此可以看出这个Expression在实际项目中用途是非常大的。

他的具体语法如下:

Expression Syntax

When you create an expression, use the ColumnName property to refer to columns. For example, if the ColumnName for one column is "UnitPrice", and another "Quantity", the expression would be as follows:

"UnitPrice * Quantity"

Note

If a column is used in an expression, then the expression is said to have a dependency on that column. If a dependent column is renamed or removed, no exception is thrown. An exception will be thrown when the now-broken expression column is accessed.

When you create an expression for a filter, enclose strings with single quotation marks:

"LastName = 'Jones'"

If a column name contains any non-alphanumeric characters or starts with a digit or matches (case-insensitively) any of the following reserved words, it requires special handling, as described in the following paragraphs.

And

Between

Child

False

In

Is

Like

Not

Null

Or

Parent

True

If a column name satisfies one of the above conditions, it must be wrapped in either square brackets or the "`" (grave accent) quotes. For example, to use a column named "Column#" in an expression, you would write either "[Column#]":

Total * [Column#]

or "`Column#`":

Total * `Column#`

If the column name is enclosed in square brackets then any ']' and '\' characters (but not any other characters) in it must be escaped by prepending them with the backslash ("\") character. If the column name is enclosed in grave accent characters then it must not contain any grave accent characters in it. For example, a column named "Column[]\" would be written:

Total * [Column[\]\\]

or

Total * `Column[]\`

User-Defined Values

User-defined values may be used within expressions to be compared with column values. String values should be enclosed within single quotation marks (and each single quotation character in a string value has to be escaped by prepending it with another single quotation character). Date values should be enclosed within pound signs (#) or single quotes (') based on the data provider. Decimals and scientific notation are permissible for numeric values. For example:

"FirstName = 'John'"

"Price <= 50.00"

"Birthdate < #1/31/82#"

For columns that contain enumeration values, cast the value to an integer data type. For example:

"EnumColumn = 5"

Parsing Literal Expressions

All literal expressions must be expressed in the invariant culture locale. When DataSet parses and converts literal expressions, it always uses the invariant culture, not the current culture.

String literals are identified when there are single quotes surrounding the value. For example:

'John'

Boolean literals are true and false; they are not quoted in expressions.

Integer literals [+-]?[0-9]+ are treated as System.Int32, System.Int64 or System.Double. System.Double can lose precision depending on how large the number is. For example, if the number in the literal is 2147483650, DataSet will first attempt to parse the number as an Int32. This will not succeed because the number is too large. In this case DataSet will parse the number as an Int64, which will succeed. If the literal was a number larger than the maximum value of an Int64, DataSet will parse the literal using Double.

Real literals using scientific notation, such as 4.42372E-30, are parsed using System.Double.

Real literals without scientific notation, but with a decimal point, are treated as System.Decimal. If the number exceeds the maximum or minimum values supported by System.Decimal, then it is parsed as a System.Double. For example:

142526.144524 will be converted to a Decimal.

345262.78036719560925667 will be treated as a Double.

Operators

Concatenation is allowed using Boolean AND, OR, and NOT operators. You can use parentheses to group clauses and force precedence. The AND operator has precedence over other operators. For example:

(LastName = 'Smith' OR LastName = 'Jones') AND FirstName = 'John'

When you create comparison expressions, the following operators are allowed:

<

>

<=

>=

<>

=

IN

LIKE

The following arithmetic operators are also supported in expressions:

+ (addition)

- (subtraction)

* (multiplication)

/ (division)

% (modulus)

String Operators

To concatenate a string, use the + character. The value of the CaseSensitive property of the DataSet class determines whether string comparisons are case-sensitive. However, you can override that value with the CaseSensitive property of the DataTable class.

Wildcard Characters

Both the * and % can be used interchangeably for wildcard characters in a LIKE comparison. If the string in a LIKE clause contains a * or %, those characters should be enclosed in brackets ([]). If a bracket is in the clause, each bracket character should be enclosed in brackets (for example [[] or []]). A wildcard is allowed at the start and end of a pattern, or at the end of a pattern, or at the start of a pattern. For example:

"ItemName LIKE '*product*'"

"ItemName LIKE '*product'"

"ItemName LIKE 'product*'"

Wildcard characters are not allowed in the middle of a string. For example, 'te*xt' is not allowed.

Parent/Child Relation Referencing

A parent table may be referenced in an expression by prepending the column name with Parent. For example, the Parent.Price references the parent table's column named Price.

When a child has more than one parent row, use Parent(RelationName).ColumnName. For example, the Parent(RelationName).Price references the parent table’s column named Price via the relation.

A column in a child table may be referenced in an expression by prepending the column name with Child. However, because child relationships may return multiple rows, you must include the reference to the child column in an aggregate function. For example, Sum(Child.Price) would return the sum of the column named Price in the child table.

If a table has more than one child, the syntax is: Child(RelationName). For example, if a table has two child tables named Customers and Orders, and the DataRelation object is namedCustomers2Orders, the reference would be as follows:

Avg(Child(Customers2Orders).Quantity)

Aggregates

The following aggregate types are supported:

Sum (Sum)

Avg (Average)

Min (Minimum)

Max (Maximum)

Count (Count)

StDev (Statistical standard deviation)

Var (Statistical variance).

Aggregates are ordinarily performed along relationships. Create an aggregate expression by using one of the functions listed earlier and a child table column as detailed in Parent/Child Relation Referencing that was discussed earlier. For example:

Avg(Child.Price)

Avg(Child(Orders2Details).Price)

An aggregate can also be performed on a single table. For example, to create a summary of figures in a column named "Price":

Sum(Price)

Note

If you use a single table to create an aggregate, there would be no group-by functionality. Instead, all rows would display the same value in the column.

If a table has no rows, the aggregate functions will return null.

Data types can always be determined by examining the DataType property of a column. You can also convert data types using the Convert function, shown in the following section.

An aggregate can only be applied to a single column and no other expressions can be used inside the aggregate.

Functions

The following functions are also supported:

CONVERT

Description

Converts particular expression to a specified .NET Framework Type.

Syntax

Convert(expression, type)

Arguments

expression -- The expression to convert.

type -- The .NET Framework type to which the value will be converted.

Example: myDataColumn.Expression="Convert(total, 'System.Int32')"

All conversions are valid with the following exceptions: Boolean can be coerced to and from Byte, SByte, Int16, Int32, Int64, UInt16, UInt32, UInt64, String and itself only. Char can be coerced to and from Int32, UInt32, String, and itself only. DateTime can be coerced to and from String and itself only. TimeSpan can be coerced to and from String and itself only.

LEN

Description

Gets the length of a string

Syntax

LEN(expression)

Arguments

expression -- The string to be evaluated.

Example: myDataColumn.Expression="Len(ItemName)"

ISNULL

Description

Checks an expression and either returns the checked expression or a replacement value.

Syntax

ISNULL(expression, replacementvalue)

Arguments

expression -- The expression to check.

replacementvalue -- If expression is null, replacementvalue is returned.

Example: myDataColumn.Expression="IsNull(price, -1)"

IIF

Description

Gets one of two values depending on the result of a logical expression.

Syntax

IIF(expr, truepart, falsepart)

Arguments

expr -- The expression to evaluate.

truepart -- The value to return if the expression is true.

falsepart -- The value to return if the expression is false.

Example: myDataColumn.Expression = "IIF(total>1000, 'expensive', 'dear')

TRIM

Description

Removes all leading and trailing blank characters like \r, \n, \t, ' '

Syntax

TRIM(expression)

Arguments

expression -- The expression to trim.

SUBSTRING

Description

Gets a sub-string of a specified length, starting at a specified point in the string.

Syntax

SUBSTRING(expression, start, length)

Arguments

expression -- The source string for the substring.

start -- Integer that specifies where the substring starts.

length -- Integer that specifies the length of the substring.

Example: myDataColumn.Expression = "SUBSTRING(phone, 7, 8)"

Note

You can reset the Expression property by assigning it a null value or empty string. If a default value is set on the expression column, all previously filled rows are assigned the default value after the Expression property is reset.

<pre name="code" class="csharp">private void CalcColumns()
{DataTable table = new DataTable ();// Create the first column.DataColumn priceColumn = new DataColumn();priceColumn.DataType = System.Type.GetType("System.Decimal");priceColumn.ColumnName = "price";priceColumn.DefaultValue = 50;// Create the second, calculated, column.DataColumn taxColumn = new DataColumn();taxColumn.DataType = System.Type.GetType("System.Decimal");taxColumn.ColumnName = "tax";taxColumn.Expression = "price * 0.0862";// Create third column.DataColumn totalColumn = new DataColumn();totalColumn.DataType = System.Type.GetType("System.Decimal");totalColumn.ColumnName = "total";totalColumn.Expression = "price + tax";// Add columns to DataTable.table.Columns.Add(priceColumn);table.Columns.Add(taxColumn);table.Columns.Add(totalColumn);DataRow row = table.NewRow();table.Rows.Add(row);DataView view = new DataView(table);dataGrid1.DataSource = view;
}

DataColumn.Expression 语法相关推荐

  1. DataTable的Compute方法和Expression语法

    DataTable的Compute的功能可谓强大. public object Compute(string expression,string filter ); expression:要执行计算的 ...

  2. 表达式计算 DataTable/DataRow/DataColumn Expression、JScript CodeDomProvider Eval

  3. JSP/Servlet基础语法

    相关学习资料 http://my.oschina.net/chape/blog/170247 http://docs.oracle.com/cd/E13222_01/wls/docs81/webapp ...

  4. 使用现代化 C# 语法简化代码

    使用现代化 C# 语法简化代码 Intro 最近几个版本的 C# 在语法中有很多的变化,有很多语法能够帮助我们大大简化代码复杂度,使得代码更加简洁,分享几个我觉得比较实用的可以让代码更加简洁的语法 D ...

  5. Groovy的基础语法

    Groovy的基础语法 Groovy 的语法融合了 Ruby.Python 和 Smalltalk 的一些最有用的功能,同时保留了基于 Java 语言的核心语法.对于Java 开发人员,Groovy ...

  6. ucc编译器(语法解析)

    [ 声明:版权所有,欢迎转载,请勿用于商业用途. 联系信箱:feixiaoxing @163.com] 做完词法分析,后面紧接着就是语法分析.对于一个编程语言而言,语法解析才是语言和语言之间最大的区别 ...

  7. 《正则表达式必知必会》读书笔记【语法整理】

    Regular Expression语法 1.纯文本匹配 word 2. .表示匹配任意一个单个字符,包括字母.数字或者点"."本身(除换行符以外的任意单个字符) apple. 3 ...

  8. IDL学习:语法基础-字符串

    1. 创建字符串 IDL中可以用单引号''或双引号""来创建字符转 >>a = 'hlz' >>b = "hlz" >>a ...

  9. DataTable的Compute功能详解

    在为筛选器创建表达式时,用单引号将字符串括起来: "LastName = 'Jones'" 下面的字符是特殊字符,如下面所解释的,如果它们用于列名称中,就必须进行转义: \n (n ...

最新文章

  1. Linux基础:让history记录命令的历史执行时间
  2. C#23种开发模式,陆续完善中
  3. Concurrent Package
  4. iOS8中提示框的使用UIAlertController(UIAlertView和UIActionSheet二合一)
  5. 数据结构——二叉树的非递归算法
  6. MVC中使用jquery uploadify上传图片报302错误
  7. 谷粒商城:01. 分布式基础项目环境搭建
  8. adb重启或关机手机命令
  9. 保证线程安全的三种方式
  10. excel单元格使用公式进行币种自动转换,亿,万,元
  11. java:布局方法(边界布局)
  12. commit翻译中文_commit的意思在线翻译,解释commit中文英文含义,短语词组,音标读音,例句,词源,同义词【澳典网ODict.Net】...
  13. CSP 202112-3 登机牌条码 (详细图解)
  14. 关于wx.downloadFile的URL 微信小程序下载文件 服务器http服务的部署
  15. Android高德地图基本开发/在线高德离线地图开发/断网使用离线地图(Assets文件夹的使用)
  16. 如何做好硕士论文的排版
  17. 【今日CV 计算机视觉论文速览 第128期】Mon, 10 Jun 2019
  18. Android 语音输入API使用
  19. 第一章创业、创业精神与人生发展
  20. python爬虫实战技巧保盈_自学Python十 爬虫实战三(美女福利续)

热门文章

  1. 亚马逊echo中国使用_如何将您的Amazon Echo购物清单发送到您的电子邮件
  2. spotify使用教程_什么是Spotify Kids? (以及如何使用其家长控制)
  3. 计算机多媒体教学,浅谈计算机专业的多媒体教学
  4. 博客园写博客时如何插入超链接
  5. dell 工作站装linux_预装Ubuntu Linux 戴尔推出全新Precision Precision移动工作站
  6. 【cocos2dx 3.2】井字过三关
  7. Java每日练习---自由落体运动
  8. 虚拟服务器伪静态怎么设置,云虚拟主机 nginx伪静态 如何设置
  9. 读懂它,简单演绎幸福生活~
  10. android studio播放视频权限,Android Studio实现本地视频播放