2-Column DataTable to List<int> .NET 2.0

馋奶兔 提交于 2019-12-11 22:36:41

问题


I have populated a DataTable from a stored procedure in an older web application written in

C# under .NET 2.0 / Visual Studio 2005.

I'm trying to populate a List with the values in the DataTable, but I keep running up against a couple issues.

My conversion process looks like this:

List<int> SpecialVendorList = new List<int>();

foreach (DataRow datarow in GetAllSpecialVendors().Rows)
{
//Loop through each row
foreach (DataColumn column in GetAllSpecialVendors().Columns)
   {
       SpecialVendorList.Add(column["ChildVendorId"]);
       SpecialVendorList.Add(column["ParentVendorId"]);
   }
}

which gives me the following error:

Can not apply indexing with [] to an expression of type 'System.Data.DataColumn'

for each of the SpecialVendorList.Add() methods.


回答1:


Seems like you're trying to get column values for each row. You only the first foreach loop:

List<int> SpecialVendorList = new List<int>();

try
{
    foreach (DataRow datarow in GetAllSpecialVendors().Rows)
    {
        //Loop through each row
       SpecialVendorList.Add(Convert.ToInt32(datarow["ChildVendorId"]));
       SpecialVendorList.Add(Convert.ToInt32(datarow["ParentVendorId"]));
    }
}
catch(FormatException fe)
{
    //handle the error
}

The string index here will get that column's value in that specific row




回答2:


you need to add the actual values from the rows using the column as the index:

List<int> SpecialVendorList = new List<int>();

foreach (DataRow datarow in GetAllSpecialVendors().Rows)
{
   //Loop through each row
   foreach (DataColumn column in GetAllSpecialVendors().Columns)
   {
      int val;
      if (int.TryParse(datarow[column].ToString(), out val))
         SpecialVendorList.Add(val);
   }
}


来源:https://stackoverflow.com/questions/7250434/2-column-datatable-to-listint-net-2-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!