Josh Josh -4 years ago 101
C# Question

Joining a Dictionary to a Datatable

I have a dictionary (see below) that has Key strings and Value strings and I want to be able to join this dictionary to my datatable using the dictionary Key (The equivilant unique field in the Datatable is called Network_ID). How can I do this? I'm hoping for a new datatable that has the original datatable information as well as two additional columns of data (key and value from the dictionary). Thanks very much.

My dictionary is of this type:

Dictionary<string, string> input = new Dictionary<string, string>();


Edited:

dt.Columns.Add("Key");
dt.Columns.Add("KeyValue");

foreach (System.Data.DataRow row in dt.Rows)
{
var networkID = (string)row["Network_ID"];

if(input.ContainsKey(networkID))
{
row["Key"] = networkID.ToString();
row["KeyValue"] = input.Values.ToString();
}

}

Answer Source

You can accomplish this by adding two columns to your data table, and looping through the rows to populate.

foreach (DataRow row in table.Rows)
{
    var networkID = (string)row["Network_ID"];
    if (input.ContainsKey(networkID))
    {
        row["NewKeyColumn"] = networkID;
        row["NewKeyValue"] = input[networkID]
    }
}

Because dictionary accesses are amortized O(1), the total join has linear performance.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download