5

I see many posts about converting the table(s) in a DataSet to a list of DataRows or other row data but I was unable to find anything about this question. This is what I came up with using .Net 3.0:

    public static List<DataTable> DataSetToList(DataSet ds)
    {
        List<DataTable> result = new List<DataTable>();

        foreach (DataTable dtbl in ds.Tables)
        {
            result.Add(dtbl);
        }

        return result;
    }

Is there a better way, excluding an extension method?

Thanks

Soenhay
  • 3,958
  • 5
  • 34
  • 60

2 Answers2

9

Based on Why LINQ casting with a Data.DataTableCollection this will work;

List<DataTable> result = new List<DataTable>(ds.Tables.Cast<DataTable>())
Community
  • 1
  • 1
Dave Anderson
  • 11,836
  • 3
  • 58
  • 79
  • Thanks for your reply. Your answer works in .Net 3.5 and above unless there is an include that I left out. I do have System.linq. I also found that in .Net 3.5 and up the following works: List list = ds.Tables.ToList(); – Soenhay Aug 13 '15 at 15:03
  • @Soenhay what is your include? I couldn't seem to use `ToList()` for some reason. Had missed you looking for a .Net 3.0 option though. – Dave Anderson Aug 17 '15 at 23:18
  • I am sorry I was mistaken, I had this extension method in my project so it is not actually in .net: /// /// /// /// /// public static List ToList(this DataTableCollection tables) { List result = new List(); foreach (DataTable dtbl in tables) { result.Add(dtbl); } return result; } – Soenhay Aug 24 '15 at 21:19
0
IEnumerable<DataTable> sequence = dt.AsEnumerable();

or

List<DataTable> list = dt.AsEnumerable().ToList();
Naveen Desosha
  • 347
  • 5
  • 12
  • 1
    What I mean is to convert a DataTableCollection into a List. dt.AsEnumerable().ToList(); returns List. – Soenhay Nov 25 '13 at 17:38