要查找特定行,您可能需要按可以唯一标识每一行的键进行搜索。
但是如果你想找到一组行,那么你想使用过滤器。
键可以同时包含不同类型的对象。所以可以过滤!
下面是一个具体的例子,它涵盖了使用 key 方法或 filter 方法分别作为 locateOneRow() 和 locateRows() 进行搜索。
using System.Data;
namespace namespace_A {
public static class cData {
public static DataTable srchTBL = new DataTable(tableName: "AnyTable");
public static DataColumn[] theColumns = {
new DataColumn("IDnum", typeof(int))
, new DataColumn("IDString", typeof(string))
, new DataColumn("DataString", typeof(string))
};
public static void DataInit(){
if (srchTBL.Columns.Count == 0) {
srchTBL.Columns.AddRange(theColumns);
srchTBL.PrimaryKey = new DataColumn[2] { srchTBL.Columns["IDnum"], srchTBL.Columns["IDstring"] };
//Data
srchTBL.Rows.Add(0, "me", "Homemaker");
srchTBL.Rows.Add(1, "me2", "Breadwinner2");
srchTBL.Rows.Add(1, "you", "Breadwinner1");
srchTBL.Rows.Add(2, "kid", "Learner");
}
}//DataInit
public static DataRow locateOneRow(){
DataInit();
object[] keyVals = new object[] {0, "me" };
return srchTBL.Rows.Find(keyVals);
}//locateOneRow - Result: the "Homemaker" row
public static DataRow[] locateRows(){ //no Primary key needed
DataInit();
return srchTBL.Select("IDnum = 1 OR IDstring = 'me'");
}//locateRows - Result: the row with "Homermaker" & the row with "Breadwinner2"
}//class
class Program {
static void Main(string[] args) {
try
{
DataRow row1 =cData.locateOneRow();
DataRow[] rows = cData.locateRows();
}catch(Exception ex){
}
} // Main
} // Program
}