1

I need to add Dictionary<string,List<string>> contents to a Data Table in C#. The Header column name should be the Key in Dictionary and the rows should be the List<string> contents. How can I get it?

Code:

DataTable new_dt = new DataTable();

//Header Columns
foreach (string item in splits)
{
    DataColumn col = new DataColumn(item, typeof(System.String));
    new_dt.Columns.Add(col);
}

foreach (DataColumn col in new_dt.Columns)
{
    //Declare the bound field and allocate memory for the bound field.
    BoundField bfield = new BoundField();

    //Initalize the DataField value.
    bfield.DataField = col.ColumnName;

    //Initialize the HeaderText field value.
    bfield.HeaderText = col.ColumnName;

    //Add the newly created bound field to the GridView.
    gvMatrix.Columns.Add(bfield);
}

//Content Loading
foreach (KeyValuePair<string, List<string>> item in _dict)
{
    string[] ss = item.Value.ToArray();

    foreach (string s in ss)
    {
        DataRow row = new_dt.NewRow();
        row[item.Key] = s;
        new_dt.Rows.Add(row);
    }
}

gvMatrix.DataSource = new_dt;
gvMatrix.DataBind();
Markus Safar
  • 6,324
  • 5
  • 28
  • 44
Farhana
  • 17
  • 5
  • 1
    What did you try to do so far? – Yacoub Massad Nov 27 '15 at 06:53
  • 3
    What is if one of the lists is not as long as the other lists? as from what you say you want to use the key as column name and the contents as the rows under it. Thus the question pops up what happens when one of the columns has a different number of rows? (from how you built the dictionary normally I would do 1 datatable PER dictionary entry there as all else is.....pandoras box literally if you can't make sure that you have the same number of entries under each key) – Thomas Nov 27 '15 at 07:08
  • One additional note: As you have added asp.net as a tag. Are you sure about that? Even if it is an asp.net program none of the code you have is asp.net specific so I don't think that that tag is necessary (as asp.net has the same dictionary/list/datatable methods available as c#) – Thomas Nov 27 '15 at 07:11
  • Please refer this link http://stackoverflow.com/questions/15293653/coverting-list-of-dictionary-to-datatable – Akhil R J Nov 27 '15 at 07:19
  • But the above link contains List of dictionaries. And in my case I am having Dictionary containing Lists – Farhana Nov 27 '15 at 07:29
  • And the output looks like... AAA BBB 1 2 10 9 – Farhana Nov 27 '15 at 07:32
  • Can I use DataSet instead? – Farhana Nov 27 '15 at 07:35
  • regardless what you want to use. Trying to process a multidimensional array into 1 single variable (regardless if its a dataset or a datatable,...) is problematic if you cannot make 100% sure that each "column" has the same numbers of entries. Else you will have to put routines in that fill up the empty values,.... and define how to treat them (if the values are the first part or the last part of the column and the empties fill up the rest,... and how the fill ups look like,....). like I said a pandoras box at best as there are special cases left and right with that. – Thomas Nov 27 '15 at 07:44

1 Answers1

0

This should work:

        Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>();
        int rowcount = table.Rows.Count;
        int columnCount = table.Columns.Count;

        for (int c = 0; c <= columnCount; c++)
        {
            string columnName = table.Columns[c].ColumnName;
            List<string> tempList = new List<string>();

            for (int r = 0; r <= rowcount; r++)
            {
                var row = table.Rows[r];
                if (row[c] != DBNull.Value)
                    tempList.Add((string)row[c]);
                else
                    tempList.Add(null);
            }
            dict.Add(columnName, tempList);
        }

But as others have mentioned, it isn't a really good idea to convert a datatable into a dictionary.The columns having different lenghts as mentioned in the comments aren't really a problem normally as you can't add values to columns, you can only add rows to a table of which you defined the columns. If you don't give a value to a certain column in the row, then it will contain DBNull.Value, if you haven't set the column to AllowDBNull = true you will get an error if you don't fill in one of the columns. So there will never be columns with more rows than the other ones because that's impossible.

Alexander Derck
  • 13,818
  • 5
  • 54
  • 76