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

时间:2015-03-10 19:04:52

标签: c# asp.net-mvc-4 datatable

我是使用DataTables的新手,并且对于为什么这不起作用感到困惑。

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

DataTable的三列是从包含以下列的SQL结果创建的:

  • Id - int,主键,不可为空
  • ParentId - int,默认为0,不可为空
  • Text - varchar(MAX),nullable

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

错误是“错误4参数1:无法从'对象'转换为'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);
    }

1 个答案:

答案 0 :(得分:2)

resultIds.Add(dr["id"])是一个动态表达式,在编译时它被视为对象,所以你必须按如下方式转换它

resultIds.Add(int.Parse(dr["id"].ToString()));