在 C# DataTable 中搜索术语列表,然后在 return 行 ID 中搜索结果

Search C# DataTable for List of terms, then return row Id for the results

我刚开始使用 DataTables,我很困惑为什么这不起作用。

我想要做的是在 DataTable 中所有行的 "text" 列中搜索 "terms"(列表)中列出的任何单词。如果找到其中一个,我想将行的Id添加到另一个列表中,"resultIds"(列表)。

DataTable 的三列是根据具有以下列的 SQL 结果创建的:

有人可以帮助我理解为什么这不起作用吗?

错误是"Error 4 Argument 1: cannot convert from 'object' to 'int'".

编辑: 现在我在尝试将 Id 添加到列表时收到 "Object reference not set to an instance of an object error"。

    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()));