This website completely moved to new platform. For latest content, visit www.programmingposts.com

Search this Site

18 Oct 2015

DataTable to Dictionary Conversion in C#.Net

In this post, here is the c# code to convert DataTable to Dictionary.
while working with DataSet or DataTable we may need key value pair to get Value by Id approach.
So you may need to convert your DataTable to key value type i.e, Dictionary.

you can also use Dictionary for data binding of controls like Dropdown list, Radio button list etc.

Here we will see a sample console program where we convert DataTable to Dictionary and print the Dictionary.
I have written 2 overrides for a method DataTabelToDictionary(). The Method code is given below:



  /// <summary>
 /// Converts DataTable to Dictionary
 /// </summary>
 /// <param name="dt">DataTable</param>
 /// <param name="keyIndex">Column Index for Dictionary Key</param>
 /// <param name="ValueIndex">Column Index for DIctionary Value</param>
 /// <returns></returns>
  public Dictionary<object, object> DataTableToDictionary(DataTable dt, int keyIndex, int ValueIndex)
 {
    return dt.AsEnumerable()
            .ToDictionary<DataRow, object, object>(row => row.Field<object>(keyIndex),
                                        row => row.Field<object>(ValueIndex));
 }

    /// <summary>
  /// Converts DataTable to Dictionary
  /// </summary>
  /// <param name="dt">DataTable</param>
  /// <param name="keyIndex">Column Name for Dictionary Key </param>
  /// <param name="ValueIndex">Column Name for Dictionary Value</param>
  /// <returns></returns>
  public Dictionary<object, object> DataTableToDictionary(DataTable dt, string keyColName, string ValColName)
  {
    return dt.AsEnumerable()
         .ToDictionary<DataRow, object, object>(row => row.Field<object>(keyColName),
                                        row => row.Field<object>(ValColName));
  }




The Program below is an example of converting DataTable to Dictionary.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;

namespace Dtable2Dict
{
    class Program
    {
        static void Main(string[] args)
        {
            Program objProg = new Program();
            DataTable dtDept = objProg.getDepartments();


            Dictionary<object, object> dicTest;
           
            //converting DataTable to Dictionary
            dicTest = objProg.DataTabelToDictionary(dtDept, "DeptId", "DeptName");

            //Converting Dictionary to our required Dictionary Type
            Dictionary<int, string> dicThruColNames = dicTest.ToDictionary(k => Convert.ToInt32(k.Key),
                                                k => k.Value == null ? "" : k.Value.ToString());

            dicTest = objProg.DataTabelToDictionary(dtDept, 0, 1);
            Dictionary<int, string> dicThruColIndex = dicTest.ToDictionary(k => Convert.ToInt32(k.Key),
                                                    k => k.Value == null ? "" : k.Value.ToString());

            //Printing Dictionary
            Console.WriteLine("\n*** www.programmingposts.com ***\n");
            Console.WriteLine("\n>>> Program for DataTable to Dictionary Conversion <<<\n");
            
            Console.WriteLine("Printing Converted Dictionary :");
            Console.WriteLine("Key || Value");
            foreach (KeyValuePair<int, string> pair in dicThruColNames)
            {
                Console.WriteLine(pair.Key + "  " + pair.Value);
            }
            Console.ReadLine();
        }

        /// <summary>
        /// returns sample DataTable
        /// </summary>
        /// <returns></returns>
        private DataTable getDepartments()
        {
            DataTable dtDept = new DataTable();
            dtDept.Columns.Add("DeptId", typeof(Int32));
            dtDept.Columns.Add("DeptName", typeof(String));
            dtDept.Columns.Add("DeptEmpCount", typeof(Int32));
            DataRow dr;

            for (int i = 1; i <= 5; i++)
            {
                dr = dtDept.NewRow();
                dr["DeptId"] = i;
                dr["DeptName"] = "Dept" + i.ToString();
                dr["DeptEmpCount"] = (i * 10);
                dtDept.Rows.Add(dr);
            }
            return dtDept;
        }

        /// <summary>
        /// Converts DataTable to Dictionary
        /// </summary>
        /// <param name="dt">DataTable</param>
        /// <param name="keyIndex">Column Index for Dictionary Key</param>
        /// <param name="ValueIndex">Column Index for DIctionary Value</param>
        /// <returns></returns>
        public Dictionary<object, object> DataTabelToDictionary(DataTable dt, int keyIndex, int ValueIndex)
        {
            return dt.AsEnumerable()
              .ToDictionary<DataRow, object, object>(row => row.Field<object>(keyIndex),
                                        row => row.Field<object>(ValueIndex));
        }

        /// <summary>
        /// Converts DataTable to Dictionary
        /// </summary>
        /// <param name="dt">DataTable</param>
        /// <param name="keyIndex">Column Name for Dictionary Key </param>
        /// <param name="ValueIndex">Column Name for Dictionary Value</param>
        /// <returns></returns>
        public Dictionary<object, object> DataTabelToDictionary(DataTable dt, string keyColName, 
                                           string ValColName)
        {
            return dt.AsEnumerable()
              .ToDictionary<DataRow, object, object>(row => row.Field<object>(keyColName),
                                        row => row.Field<object>(ValColName));
        }
    }

}

output:

No comments:

Post a Comment

Thanks for your comments.
-Sameer