【问题标题】:Looping through rows in DataTable and extracting element in C#循环遍历 DataTable 中的行并在 C# 中提取元素
【发布时间】:2015-05-27 11:06:22
【问题描述】:

我想把DataTable中列的项目提取出来放到List中。

这是我的列表和数据表:

List<int> product1 = new List<int>();
DataTable table = this.IoC.Resolve<ISurveyResultsService>().GetProduct(studyYear, productName);

我想遍历 DataTable 并将元素放入列表中。我试过这样:

foreach (var row in table.Rows)
{
    product.Add((int)row["StudyID"]);
}

我收到一条错误消息“无法使用 [] 将索引应用于 'object' 类型的表达式”

知道如何尽可能简单地解决这个问题吗?

【问题讨论】:

标签: c# datatable datarow


【解决方案1】:

你需要像这样在 foreach 循环中进行转换:

foreach (DataRow row in table.Rows)

请注意,foreach 中的类型定义充当强制转换。现在你有了一个允许[] 的类型。


您还可以使用 Linq 使其看起来更干净:

List<int> product = table.Rows.Cast<DataRow>().Select(row => (int)row["StudyID"]).ToList()

【讨论】:

    【解决方案2】:
    foreach (DataRow row in table.Rows)
    {
        product.Add((int)row["StudyID"]);
    }
    

    foreach (var row in table.AsEnumerable())
    {
        product.Add((int)row["StudyID"]);
    }
    

    products = table.AsEnumerable().Select(row=>(int)row["StudyID"]).ToList();
    

    【讨论】:

      【解决方案3】:

      您正在将表格行转换为var 对象。将其转换为DataRow 试试

      foreach(DataRow row in table.Rows)
      {
          product.Add((int)row["StudyID"]);
      }
      

      【讨论】:

        【解决方案4】:

        这里是代码

          Person p=new Person();
          foreach(DataRow row in YourDataTable.Rows)
          { 
           p.name = row["name"].ToString();
           p.description = row["description"].ToString();
           lst.Add(p);
        
        }
        

        lst 是列表<.person>

        【讨论】:

          【解决方案5】:

          只需将 var 行替换为 DataRow 行即可:

          foreach (DataRow row in table.Rows)
                  {
                      product.Add((int)row["StudyID"]);
                  }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2021-11-18
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2010-09-15
            • 1970-01-01
            相关资源
            最近更新 更多