J. Davidson
J. Davidson

Reputation: 3307

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.

Upvotes: 3

Views: 5627

Answers (3)

deostroll
deostroll

Reputation: 11975

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

Upvotes: 0

Sunny
Sunny

Reputation: 4809

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

Upvotes: 2

zimdanen
zimdanen

Reputation: 5626

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?

Upvotes: 0

Related Questions