3

I have a dynamically generated datatable, so 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?

0

2 Answers 2

3

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]);
        }
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Yes I know, but like I said, I do not want to use DataRow as the type.
Ideally I would like a List<> object created but I don't know how to do this with unknown column names
If I were you I'd either just use the normal version, or use a List<Dictionary<dynamic>> or something.
3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.