开发者

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

开发者 https://www.devze.com 2023-02-18 00:35 出处:网络
I have a dynamically generated datatable, so 开发者_JS百科I don\'t know the number of columns it contains. I would like to build an IEnumerable object that contains the columnname and value for each f

I have a dynamically generated datatable, so 开发者_JS百科I don't know the number of columns it contains. I would like to build an IEnumerable object that contains the columnname and value for each field in each row.

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

Is there a way to do this?


It's already enumerable, why try to make it enumerable when it already is:

// 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]);
        }
    }
}


Since I don't really understand what you are trying to accomplish; or rather what your end goal is, I did this as a fun little exercise. I used an extension method; but there's probably ways to improve upon 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 output looks like this...

Last Name, Tim
First Name, Taylor

Last Name, John
First Name, Adams
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号