简体   繁体   中英

Converting DataTable to Generic List<T>

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.

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();

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 ?

var lst = from x in dt.AsEnumerable() 
where x.Field <string>("PersonName") == "ching" select x;

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