Skip to content

Instantly share code, notes, and snippets.

@lockworld
Last active February 27, 2018 20:52
Show Gist options
  • Save lockworld/79fe0d70b5c5cae8dd7d59701f3f5cc0 to your computer and use it in GitHub Desktop.
Save lockworld/79fe0d70b5c5cae8dd7d59701f3f5cc0 to your computer and use it in GitHub Desktop.
Iterating through dataset in C#
using System;
using System.Data;
class Program
{
static void Main()
{
DataTable table1 = new DataTable("patients");
table1.Columns.Add("name");
table1.Columns.Add("id");
table1.Rows.Add("sam", 1);
DataTable table2 = new DataTable("medications");
table2.Columns.Add("id");
table2.Columns.Add("medication");
table2.Rows.Add(1, "atenolol");
table2.Rows.Add(6, "trifluoperazine");
// Create a DataSet.
DataSet set = new DataSet("office");
set.Tables.Add(table1);
set.Tables.Add(table2);
// Loop over DataTables in DataSet.
DataTableCollection collection = set.Tables;
for (int i = 0; i < collection.Count; i++)
{
DataTable table = collection[i];
Console.WriteLine("{0}: {1}", i, table.TableName);
}
// Write name of first table.
Console.WriteLine("x: {0}", set.Tables[0].TableName);
// Write row count of medications table.
Console.WriteLine("y: {0}", set.Tables["medications"].Rows.Count);
// Get names of all columns
foreach(DataColumn column in set.Tables[0].Columns)
{
Console.WriteLine(column.ColumnName);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment