Search code examples
.netdatatabledatarowdatacolumn

DataTable DataRow DataColumn for columns


I am dumping a cvs file into a datatable. I am able to loop through each row and each column. I only do run some some logic for 4 columns out of 16 columns. I tried if but not working. How do i use "for" type syntax? For example, I like to say for columnA do this. For columnB do this. (instead of if(column.ColumnName == "ColumnA") then do something)


Solution

  • I believe you're stuck with testing the column name against some string value. Even if someone comes up with a lambda expression, it's all essentially the same thing: looping and string comparisons.

    foreach(DataRow row in table.Rows)
    {
        foreach(DataColumn col in table.Columns)
        {
            switch (col.Name)
            {
                case "ColumnA":
                      // do something
                      // if(row[col.Name] = ??) { ... }
                      break;
                case "ColumnB":
                      // do something else
                      break;
            }
        }
    }