c#: November 2009 Archives

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 this Archive

This page is a archive of entries in the c# category from November 2009.

c#: June 2009 is the previous archive.

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

Powered by Movable Type 5.04