DataTable Key/Value columns to Dictionary

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

Leave a comment

About this Entry

This page contains a single entry by Rob published on November 19, 2009 9:54 AM.

Outlook 2010 Beta - "Not Implemented" on Send/Receive was the previous entry in this blog.

Outlook 2010 Beta - Still not implemented is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.

Powered by Movable Type 4.23-en