3

I am trying to convert a Data table to a generic List. I am following this post. DataTable to List<object>.

Method is 
 public static List<MProps> TableToList<T1>(DataTable dt)
        {
                if (dt == null)
            {
                return null;
            }
            List<DataRow> rows = new List<DataRow>();
            foreach (DataRow row in dt.Rows)
            {
                rows.Add(row);
            }
            return TableToList<T1>(rows);
        }

I keep getting two errors at "return TableToList<T1>(rows);" Saying 
Error 24 Argument 1: cannot convert from 'System.Collections.Generic.List<System.Data.DataRow>' to 'System.Data.DataTable' C:\Users..\Program.cs    

AND 

Error 23 The best overloaded method match for 'xx.Program.TableToList<T1>(System.Data.DataTable)' has some invalid arguments C:\Users\--\Program.cs

I cant figure out what is the problem.

Community
  • 1
  • 1
J. Davidson
  • 3,297
  • 13
  • 54
  • 102

3 Answers3

2

Use

List<DataRow> rows = dt.AsEnumerable().ToList();

If you need to return List

return (from DataRow row in dt.Rows
   select new MProps
   {
       //assign properties here
       prop1 = row["colname"].ToString()
   }).ToList();
Sunny
  • 4,765
  • 5
  • 37
  • 72
0

In your return, you're trying to call the method again, but you're passing rows, which is a List<DataRow>. Your method expects a DataTable, so it's telling you that you're calling your method incorrectly.

Theoretically, you should be making a List<MProps> and returning that, rather than making a List<DataRow> and calling TableToList. Perhaps make a DataRowToMProp method and call that for every DataRow?

zimdanen
  • 5,508
  • 7
  • 44
  • 89
0
var lst = from x in dt.AsEnumerable() 
where x.Field <string>("PersonName") == "ching" select x;
deostroll
  • 11,661
  • 21
  • 90
  • 161