简体   繁体   中英

Efficient way to check for data tables in a data set

public void Method1()
{
  Datatable dt1 = new DataTable();
  Datatable dt2 = new DataTable();
  Datatable dt3 = new DataTable();

if (ds.Tables.Count > 0)
{       
         if (ds.Tables[0].Rows.Count > 0)
            dt1 = ds.Tables[0];
         if (ds.Tables[1].Rows.Count > 0)
              dt2 = ds.Tables[1];
          if (ds.Tables[2].Rows.Count > 0)
              dt3 = ds.Tables[2];              
}
}

In the code above is there a better way to check for exact number of tables in the dataset "ds", whenever ds has three tables there is no issue but if it has one table it fails on second if condition and throws an exception Cannot find Table1. Any pointers on checking if that tables exists or not.

Thank you.

There are several ways to do this. For example you can do the following, if you still want three DataTable objects:

public void Method1()
{
    DataTable dt1 = ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0 ? ds.Tables[0] : new DataTable();
    DataTable dt2 = ds.Tables.Count > 1 && ds.Tables[1].Rows.Count > 0 ? ds.Tables[1] : new DataTable();
    DataTable dt3 = ds.Tables.Count > 2 && ds.Tables[2].Rows.Count > 0 ? ds.Tables[2] : new DataTable();
}

A more dynamic way would be to store all tables in a list like this:

public void Method1()
{
    List<DataTable> dataTables = new List<DataTable>();

    foreach (DataTable dataTable in ds.Tables)
    {
        if (dataTable.Rows.Count > 0) dataTables.Add(dataTable);
    }

}

or by using Linq

public void Method2()
{
    List<DataTable> dataTables = ds.Tables.Cast<DataTable>().Where(dataTable => dataTable.Rows.Count > 0).ToList();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM