Is it possible to build an object from a dynamic datatable?

I have a dynamically generated datatable, so I don't know the number of columns it contains. I would like to create an IEnumerable object that contains the column name and value for each field in each row.

I do not want to use the DataRow object as a type.

Is there any way to do this?

+3
source share
2 answers

It is already enumerated, why try to make it enumerable when it is already there:

// Results = DataSet
foreach (DataTable table in results.Tables)
{
    Console.WriteLine("Table: " + table.TableName);
    foreach (DataRow row in table.Rows)
    {
        Console.WriteLine("  Row");
        foreach (DataColumn column in table.Columns)
        {
            Console.WriteLine("    " + column.ColumnName + ": " +
                row[column]);
        }
    }
}
+3
source

Since I really do not understand what you are trying to achieve; or rather, your final goal, I did it as a fun exercise. I used the extension method; but there are probably ways to improve it ...

public static class DataTableExtension
{
    public static IEnumerable<IEnumerable<KeyValuePair<string, object>>> Items(this DataTable table)
    {
        var columns = table.Columns.Cast<DataColumn>().Select(c => c.ColumnName);
        foreach (DataRow row in table.Rows)
        {
            yield return columns.Select(c => new KeyValuePair<string, object>(c, row[c]));

        }
    }
}

static void Main(string[] args)
    {
        DataTable table = new DataTable();
        table.Columns.Add("Last Name");
        table.Columns.Add("First Name");
        table.Rows.Add("Tim", "Taylor");
        table.Rows.Add("John", "Adams");
        foreach (var row in table.Items())
        {
            foreach (var col in row)
            {
                Console.WriteLine("{0}, {1}\t", col.Key, col.Value);
            }

            Console.WriteLine();
        }

        Console.ReadLine();
    }

The result looks like this:

Last Name, Tim
First Name, Taylor

Last Name, John
First Name, Adams
+3
source

All Articles