有些.NET程序員采取在數據庫中建立臨時表等方法來解決這類查詢問題。而我覺得這種方法不可行,其實只要用.Net類庫中提供的DataView類的強大功能(主要是用它的RowFilter屬性),就能方便地解決這類查詢問題。下面就舉一個具體的例子,來說明如何不用SQL語句,用DataVIEw的RowFilter屬性來查詢。
步驟一:建立一個C#的ASP.Net項目。先編寫一個生成DataTable的函數MakeDataTable(),代碼如下:
private DataTable MakeTable()
{
//生成DataTable
System.Data.DataTable myDataTable = new DataTable("本地數據表");
DataColumn myDataColumn;
DataRow myDataRow;
//生成數據列 ID,商品名稱,商品價格
myDataColumn = new DataColumn();
myDataColumn.DataType = System.Type.GetType("System.Int32");
myDataColumn.ColumnName = "ID";
myDataColumn.ReadOnly = true;
myDataColumn.Unique = true;
myDataTable.Columns.Add(myDataColumn);
myDataColumn = new DataColumn();
myDataColumn.DataType = System.Type.GetType("System.String");
myDataColumn.ColumnName = "商品名稱";
myDataTable.Columns.Add(myDataColumn);
myDataColumn = new DataColumn();
myDataColumn.DataType =System.Type.GetType("System.Decimal");
myDataColumn.ColumnName = "商品價格";
myDataTable.Columns.Add(myDataColumn);
//為數據表添加數據行
myDataRow = myDataTable.NewRow();
myDataRow["id"] = 1;
myDataRow["商品名稱"] = "足球";
myDataRow["商品價格"] =57.5;
myDataTable.Rows.Add(myDataRow);
myDataRow = myDataTable.NewRow();
myDataRow["id"] = 2;
myDataRow["商品名稱"] = "籃球";
myDataRow["商品價格"] =64.5;
myDataTable.Rows.Add(myDataRow);
myDataRow = myDataTable.NewRow();
myDataRow["id"] = 3;
myDataRow["商品名稱"] = "網球";
myDataRow["商品價格"] =6.5;
myDataTable.Rows.Add(myDataRow);
myDataRow = myDataTable.NewRow();
myDataRow["id"] = 4;
myDataRow["商品名稱"] = "網球拍";
myDataRow["商品價格"] =388.5;
myDataTable.Rows.Add(myDataRow);
//返回數據表
return myDataTable;
}