Skip to content

Instantly share code, notes, and snippets.

@booyaa
Created September 25, 2013 15:11
Show Gist options
  • Save booyaa/6701087 to your computer and use it in GitHub Desktop.
Save booyaa/6701087 to your computer and use it in GitHub Desktop.
DataTable Magick

DataTable Magick

Rapid DataTable creation

DataTable dtConfig = new DataTable("CONFIG");
dtConfig.Columns.Add(new DataColumn("key", typeof(System.String)));
dtConfig.Columns.Add(new DataColumn("value", typeof(System.String)));
dtConfig.Rows.Add("foo", "bar");
dtConfig.Rows.Add("connString", "Data Source=urmum");

Will give you a datatable like this

|key       |value            |
|----------|-----------------|
|foo       |bar              |
|connString|Data Source=urmum|

DT to Dictionary

Assume that we're using the dtConfig from the last example

var config =  (from row in dtConfig.AsEnumerable()
                  select new
                  {
                      key = row.Field<string>("key"),
                      value = row.Field<string>("value")
                  }
                ).AsEnumerable().ToDictionary(k => k.key, v => v.value);

Console.WriteLine("connString: {0}",config["connString"]);

Filtering and sorting

string whereClause = @"FOO = '123'";
string orderBy = "BAR DESC";
dt.Select(whereClause, orderBy);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment