2

I have a DataTable with 4 Columns (Name, Contact, Address, Marks). I want to convert my DataTable to a List<KeyValuePair<String, int>>. I would like to add Name and Marks in that. I was looking at this question but there is no exact answer to what I'm after.

Can someone please tell me how I could convert the data table without using Linq. The List could have duplicate records so I am thinking to use Tuple. If it is possible with that then please help me with some examples.

Community
  • 1
  • 1
Rocky
  • 4,454
  • 14
  • 64
  • 119

2 Answers2

4

This should do it. dt is of course the name of your datatable. You might also want to do dr["ColName"] instead of dr[0] :)

    List<KeyValuePair<String, int>> test = new List<KeyValuePair<string, int>>();
    foreach (DataRow dr in dt.Rows)
    {
        test.Add(new KeyValuePair<string, int>(dr[0].ToString(), Convert.ToInt16(dr[3])));
    }
WozzeC
  • 2,630
  • 1
  • 13
  • 12
0

This is off my head but:

public static List<KeyValuePair<string, int>> ConvertRowsToList(DataTable input) {
  var ret = new List<KeyValuePair<string, int>>();

  foreach(DataRow dr in input.Rows)
    ret.Add(new KeyValuePair<string, int>((string)dr["Name"], (int)dr["Marks"]));

  return ret;
}
Jcl
  • 27,696
  • 5
  • 61
  • 92