Attaching a Dictionary to a Datatable

I have a dictionary (see below) with key and Value strings and I want to join this dictionary to my datatable using the dictionary key (the unique unique field in Datatable is called Network_ID). How can i do this? I hope for a new data type that has the original data information, as well as two additional data columns (key and value from the dictionary). Many thanks.

My dictionary of this type: Dictionary<string, string> input = new Dictionary<string, string>();

Edited by:

         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();
            }

        }
+5
source share
4 answers

This can be done by adding two columns to the data table and scrolling through the rows to fill.

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

Since vocabulary access is depreciated by O (1), the common mix has linear performance.

+1
source

( LINQ), DataTable, IEnumerable .

       var result = from myDataRow in myDataTable.AsEnumerable()
                    join myKeyValuePair in myDictionary
                    on myDataRow.Field("Network_ID") equals myKeyValuePair.Key
                    select new { 
                        NetworkID = myDataRow.Field("Network_ID"),
                        ... /* other DataTable row values here */,
                        DictionaryKey = myKeyValuePair.Key,
                        DictionaryValue = myKeyValuePair.Value
                    };

, :) , result LINQ.

+2

, DataTable, .

DataTable ( DataSet) , DataTable, , LINQ LINQ ( , ), .

You should note that none of this can return to the database if you require this information to be stored. All this will be transient in your application.

0
source

something like:

var result = dt.AsEnumerable()
                .Join(id2itm.Keys,
                        row => row[idScColIdx],
                        id => id,
                        (row, id) => row)
                .Each(ro => {ro[idClmName] = FlagChar;
                            ro[idColorClmName] = FlagColor;});

My Each () is an extension method, you can use clean code:

var result = dt.AsEnumerable()
                .Join(id2itm.Keys,
                        row => row[idScColIdx],
                        id => id,
                        (row, id) => row);

foreach (var ro in result)
{
               ro[idClmName] = FlagChar;
               ro[idColorClmName] = FlagColor;});
}
0
source

All Articles