2

I want to extract items of the column in DataTable and put them in List.

This are my List and DataTable:

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

I want to loop through the DataTable and put elements in the list. I tried like this:

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

I get an error "Cannot apply indexing with [] to an expression of type 'object'"

Any idea how to fix that as simple as possible?

Cœur
  • 37,241
  • 25
  • 195
  • 267
jozhe
  • 197
  • 10
  • 1
    check this out http://stackoverflow.com/questions/1346132/how-do-i-extract-data-from-a-datatable – user786 May 27 '15 at 11:08

5 Answers5

4

You need to cast it in the foreach loop like this:

foreach (DataRow row in table.Rows)

Note that type definition in a foreach acts as a cast. Now you have a type that allows [].


You can also use Linq to make it look cleaner:

List<int> product = table.Rows.Cast<DataRow>().Select(row => (int)row["StudyID"]).ToList()
bytecode77
  • 14,163
  • 30
  • 110
  • 141
1
foreach (DataRow row in table.Rows)
{
    product.Add((int)row["StudyID"]);
}

or

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

or

products = table.AsEnumerable().Select(row=>(int)row["StudyID"]).ToList();
ASh
  • 34,632
  • 9
  • 60
  • 82
0

You are converting table row as var object.Convert it as DataRow try

foreach(DataRow row in table.Rows)
{
    product.Add((int)row["StudyID"]);
}
Sachu
  • 7,555
  • 7
  • 55
  • 94
0

Here is the code

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

}

lst is list<.Person>

user786
  • 3,902
  • 4
  • 40
  • 72
0

Just replace the var row with DataRow row:

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