[英]Check if String / Record exists in DataTable
我有一個字符串,我需要檢查DataTable dtPs.Rows中的任何列“item_manuf_id”是否等於某個值
我可以遍歷所有行並進行比較
String id = dtPs.Rows[number]["item_manuf_id"].ToString()
if ("some value".equals(id)) etc.
但我想知道是否有辦法檢查DataTable
包含記錄
像這樣的東西
string find = "item_manuf_id = 'some value'";
DataRow[] foundRows = table.Select(find);
您可以循環遍歷DataTable
每一行並檢查該值。
在使用IEnumerable
時,我非常喜歡使用foreach循環。 查看或處理每一行非常簡單和干凈
DataTable dtPs = // ... initialize your DataTable
foreach (DataRow dr in dtPs.Rows)
{
if (dr["item_manuf_id"].ToString() == "some value")
{
// do your deed
}
}
或者,您可以為您的DataTable
使用PrimaryKey
。 這有助於各種方式,但您通常需要先定義一個,然后才能使用它。
如果在http://msdn.microsoft.com/en-us/library/z24kefs8(v=vs.80).aspx使用一個示例
DataTable workTable = new DataTable("Customers");
// set constraints on the primary key
DataColumn workCol = workTable.Columns.Add("CustID", typeof(Int32));
workCol.AllowDBNull = false;
workCol.Unique = true;
workTable.Columns.Add("CustLName", typeof(String));
workTable.Columns.Add("CustFName", typeof(String));
workTable.Columns.Add("Purchases", typeof(Double));
// set primary key
workTable.PrimaryKey = new DataColumn[] { workTable.Columns["CustID"] };
一旦定義了主鍵並填充了數據,就可以使用Find(...)方法獲取與主鍵匹配的行。
看看http://msdn.microsoft.com/en-us/library/y06xa2h1(v=vs.80).aspx
DataRow drFound = dtPs.Rows.Find("some value");
if (drFound["item_manuf_id"].ToString() == "some value")
{
// do your deed
}
最后,您可以使用Select()方法在DataTable
查找數據,該DataTable
也位於http://msdn.microsoft.com/en-us/library/y06xa2h1(v=vs.80).aspx 。
String sExpression = "item_manuf_id == 'some value'";
DataRow[] drFound;
drFound = dtPs.Select(sExpression);
foreach (DataRow dr in drFound)
{
// do you deed. Each record here was already found to match your criteria
}
我認為如果你的“item_manuf_id”是DataTable的主鍵,你可以使用Find方法......
string s = "stringValue";
DataRow foundRow = dtPs.Rows.Find(s);
if(foundRow != null) {
//You have it ...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.