LINQ to Object (Load Dictionary/HashTable from DataTable)

Code to load data of DataTable in the Dictionary object (Considering there atleast one column which is containing unique values).

Consider a dictionary dicDetail which is to be loaded by the values available in a data table. I am considering that a table dtSample is containing 2 columns(RollNo, Name). Now our task is to load the data in the dictionary dicDetail. In which RollNo will be key and Name will be value.



Dictionary<string, String> dicDetail = new Dictionary<string, String>();
Function to load dictionary from datatable dt

private int Load_DictionaryTable_LINQ(DataTable dt)
{
         var count = (from dr in dt.AsEnumerable()
     select new{
                a = updateDictionary(dr.Field<String>("RollNo"), dr.Field<String>("Name"))
               }).Count();
     return (int)count;
}

public int updateDictionary(string key, string value)
{      if (dicDetail.ContainsKey(key))
      {
          dicDetail[key] = value;
      }
      else
      {
          dicDetail.Add(key, value);
      }
   return 1;
}

No comments:

Post a Comment