DataTable Key/Value columns to Dictionary

There are undoubtedly more elegant ways to do this using LINQ, but to quickly and easily take the key (int) and value (string) columns from a DataTable and turn them into a Dictionary<int, string>, the following method has come in handy recently:

public static Dictionary<int, string> GetAsDictionary(DataTable data, string keyField, string valueField)
{
    Dictionary<int, string> dictionary = new Dictionary<int, string>();
    foreach (DataRow row in data.Rows)
    {
         dictionary.Add(Convert.ToInt32(row[keyField]), Convert.ToString(row[valueField])); }     return dictionary;
}

About Rob

I've been interested in computing since the day my Dad purchased his first business PC (an Amstrad PC 1640 for anyone interested) which introduced me to MS-DOS batch programming and BASIC.

My skillset has matured somewhat since then, which you'll probably see from the posts here. You can read a bit more about me on the about page of the site, or check out some of the other posts on my areas of interest.

No Comments

Add a Comment