Tuesday, October 16, 2012

Selecting Columns in a Data Table in C#

“How to select multiple columns in a Data Table” … This is one of the questions asked by a reader in my article published at C# Corner site:
http://www.c-sharpcorner.com/UploadFile/0f68f2/querying-a-data-table-using-select-method-and-lambda-express/

So, I am showing here how we can do this. Here are three ways by which we could select multiple columns in a DataTable object.

(1) Using LINQ

This is a quite flexible way to do this. In this approach, we could do a lot using LINQ e.g. setting filter criteria over the rows, making joins of the table etc.     

   1:  var query = (
   2:                              from r in dt.AsEnumerable()
   3:                              select new
   4:                              {
   5:                                  SSN = r["SSN"].ToString(),
   6:                                  NAME = r["NAME"].ToString(),
   7:                              }
   8:                          ).ToList();
   9:   
  10:              foreach (var item in query)
  11:              {
  12:                  Console.WriteLine(item.SSN + "\t" + item.NAME);
  13:              }
 
(2) Using DataView class:

This is also a way to get a the view on Data table.

   1:              DataView view = new DataView(dt);
   2:              DataTable distinctValues = view.ToTable("dt", true, "SSN", "NAME");
   3:   
   4:              foreach (DataRow o in distinctValues.Select())
   5:              {
   6:                  Console.WriteLine("\t" + o["SSN"] + "\t" + o["NAME"]);
   7:              }

(3) Using DataTable.Rows collection

If we use this approach, we don’t have much scope. We could only enumerate the rows, read the rows, edit the rows like that…

   1:              for (int i = 0; i < dt.Rows.Count; i++)
   2:              {
   3:                  Console.WriteLine(dt.Rows[i]["SSN"]+ "\t"+ dt.Rows[i]["NAME"]);
   4:              }
 

2 comments: