2012-08-14 61 views
7

存在我有一個字符串,我需要檢查,如果DataTable中dtPs.Rows任何一列「item_manuf_id」等於某個值檢查字符串/記錄DataTable中

我可以遍歷所有行和比較

String id = dtPs.Rows[number]["item_manuf_id"].ToString() 
if ("some value".equals(id)) etc. 

但我想知道是否有任何的方式來檢查,如果DataTable包含記錄

回答

14

像這樣的事情

string find = "item_manuf_id = 'some value'"; 
DataRow[] foundRows = table.Select(find); 
1

我認爲,如果你的「item_manuf_id」是您可以使用Find方法DataTable的主鍵...

string s = "stringValue"; 
DataRow foundRow = dtPs.Rows.Find(s); 
if(foundRow != null) { 
//You have it ... 
} 
4

使用Find方法,如果item_manuf_id是一個主鍵:

var result = dtPs.Rows.Find("some value"); 

如果你只是想知道,如果該值在那裏再使用Contains方法。

if (dtPs.Rows.Contains("some value")) 
{ 
    ... 
} 

主鍵限制也適用於Contains也。

4

您可以遍歷DataTable的每一行並檢查值。

我很喜歡使用foreach循環時使用IEnumerable s。使得它非常簡潔乾淨看或處理每一行

DataTable dtPs = // ... initialize your DataTable 
foreach (DataRow dr in dtPs.Rows) 
{ 
    if (dr["item_manuf_id"].ToString() == "some value") 
    { 
     // do your deed 
    } 
} 

或者您可以使用一個PrimaryKeyDataTable。這有助於以各種方式,但在使用它之前,您經常需要定義一個。

如果在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"] }; 

使用中的一個例子一旦你有一個主鍵定義和填充的數據,你可以使用查找(...)方法來獲得匹配的行您首要的關鍵。

看看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 
} 

最後,你可以使用選擇()方法查找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 
} 
+1

我想從這個 – Andrew 2012-08-14 22:08:45

+0

@Kirk是[延伸](http://stackoverflow.com/a/34438198/2404470)有用了嗎? – xameeramir 2015-12-23 14:54:48