[英]Search C# DataTable for List of terms, then return row Id for the results
我是使用DataTables的新手,並對為什么這不起作用感到困惑。
我想做的是在DataTable中所有行的“ text”列中搜索“ terms”(列表)中列出的任何單詞。 如果找到其中一個,則要將行的ID添加到另一個列表“ resultIds”(列表)。
DataTable的三列是從具有以下列的SQL結果中創建的:
有人可以協助我了解為什么這行不通嗎?
錯誤為“錯誤4參數1:無法從'object'轉換為'int'”。
編輯:現在,當我嘗試將ID添加到列表中時,我收到“對象引用未設置為對象錯誤的實例”。
public ActionResult Search(MyModel model)
{
// This string gets passed in as part of the Model from the View
string delimitedText = model.text.Replace(" ", ",");
// Convert the comma delimited string into a List<>.
List<string> terms = delimitedText.Split(',').ToList();
// List<> to hold all Ids for matched DataTable rows
List<int> resultIds = null;
// Populate the DataTable with SQL result set
DataTable dt = TableDAO.Search();
// For each term in the "terms" List<>
foreach (string term in terms)
{
// Search each DataRow in the DataTable
foreach (DataRow dr in dt.Rows)
{
// If the DataRow's column "text" contains the current term in the "terms" List<>...
if (dr["text"].ToString().Contains(term))
{
// Error: "Object reference not set to an instance of an object", happens with resultIds.Add((int)dr["id"]); as well.
resultIds.Add((int)dr.ItemArray[0]);
}
}
}
return RedirectToAction("Index", resultIds);
}
resultIds.Add(dr["id"])
是一個動態表達式,在編譯時它被視為對象,因此您必須按以下方式對其進行轉換
resultIds.Add(int.Parse(dr["id"].ToString()));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.