Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping a datatable columnwise

Tags:

c#

asp.net

I have a datatable which contains data in the following format: Let us name this datatable as dt1

ColumnA       ColumnB        ColumnC
-------------------------------------
President     Manager        President
                             Manager

The data in the datatable above is provided for selection for authority selection purpose as a checklist on a web form. When the items in the checklist are checked and a button click occurs, I insert the checked items into another datatable as shown below: Let us name this datatable as dt2

 ----------
  Manager
  President
  Manager

Now I need to get the Column Names from dt1(the first datatable) where the dataitems in dt2 occurs.For example, in this scenario my required output to another datatable(say dt3) would be

--------
ColumnB
ColumnC
ColumnC

In this datatable(dt3) 'ColummB' is included as the dt2(which contains the checked texts from the checklist) has the data item 'Manager' which occurs under 'ColumnB' in dt1; 'ColumnC' occurs twice as dt2 contains 'President' and 'Manager' which occurs under 'ColumnC' in dt1.

I need an efficient loop(preferably coulmnwise for dt1) so that i can compare the values of dt1 and dt2 and add them to dt3. Please note that the data items in dt1 and dt2 are not fixed as dt1 contains data from the database and dt2 has checked values from the form. Finally the row count of the dt3 should be equal to row count of dt2 (or) a new column can be added to dt2 instead of creating dt3(still maintaining the same row count).

like image 717
Rohit Kiran Avatar asked Jun 04 '26 09:06

Rohit Kiran


1 Answers

An idea could be loop through each row and column of datatable.
Then loop through the second datatable values
If value match select the column name.

Below is just and idea what you can do

 DataTable dt1;
 DataTable dt2;
 DataTable dt3;
 string[] ar=new string....

 foreach (DataRow dr in dt1.Rows)
 {
      foreach (DataColumn clm in dt1.Columns)
      {
          //loop through each value of the other table
          foreach(DataRow drow in dt2.Rows)
          {
               string value = drow[0].ToString();
               if(value==clm)
               {
                    //add the column name into a array
                     DataRow row = dt3.NewRow();
                     row[0]=clm.ColumnName;
                     dt3.Rows.Add(row);
                     break;
               } 
          }
      }
 }
like image 80
शेखर Avatar answered Jun 05 '26 22:06

शेखर