0

I am looking for a way to loop a DataSet to fill a set List the data in the the DataSet could be in multiple DataTables in the DataSet. I have a object that has the list of column names that are needed. If I loop the object to the Dataset it will not work.

public List<Customer> BuildCustomerListMultiFile(DataSet ds, Customer oCustomer)
    {
        List<Customer> lCustomers = new List<Customer>();
        foreach (PropertyInfo p in typeof(Customer).GetProperties())
        {
            Customer oC = new Customer();
            foreach(DataTable dt in ds.Tables)
            { 
                foreach (DataRow dr in dt.Rows)
                {

                    foreach (DataColumn dc in dt.Columns)
                    {
                        if (p.Name == dc.ColumnName)
                        {
                            p.SetValue(oC, dr[dc].ToString());
                        }
                    }
                }
            }
            lCustomers.Add(oC);
        }
        return lCustomers;
    }

I did look at How to Convert DataTable to List using Reflections This will work if I am using a DataTable but I am not sure how to make it work with a DataSet which has multiple DataTables.

Community
  • 1
  • 1
Tim Morford
  • 101
  • 1
  • 11

1 Answers1

1

Just add one more loop by datatables of dataset:

foreach(DataTable dt in ds.Tables)
{
    foreach(DataRow dr in dt.Rows)
    {
        Customer oC = new Customer(); 

        foreach(DataColumn dc in dt.Columns)
        {
            if(p.Name == dc.ColumnName)
            {
                p.SetValue(oC, dr[dc].ToString());
            }
        }

        lCustomers.Add(oC);  
    }
}

Also note: you're creating and adding to list your oC outside of loop iterating the rows. So regardless of rows count in your datatable only one object will be added into list.

It looks like this should be inside loop iterating over rows.

Andrey Korneyev
  • 26,353
  • 15
  • 70
  • 71
  • The solution you proved will not work, if the data is in a different Datatable the list will be populated with missing data. – Tim Morford Apr 28 '15 at 15:37
  • @TimMorford not sure if I've got your point. Can you provide some sample structure of dataset with multiple tables you're expecting? Why do you think it will be some "missing data"? – Andrey Korneyev Apr 28 '15 at 15:43