locked
Convert DataTable to IList<SomeType> using LINQ

    Question

  • Hi, is it possible to convert a DataTable to a generic IList (IList<SomeType>) using LINQ? I could write my own function use Reflection to solve this but I am looking for some builtin solution. Thanks in advance.


    Thanks
    Tanvir.
    Friday, October 24, 2008 1:25 PM

All replies

  • There is an extension method AsDataView http://msdn.microsoft.com/en-us/library/bb907985.aspx which returns a DataView and that implements IList.

     

    Friday, October 24, 2008 1:51 PM
  • Can you please explain a little more? Shal I have to extend data view and override some function?



    Thanks
    Tanvir.
    Saturday, October 25, 2008 6:47 AM
  • public static class Util
    {
             public static List<T> toList<T>(this DataTable table)
            {
                    List<T> list = new List<T>();

                    T item ;
                    Type listItemType = typeof(T);

                    for (int i = 0; i < table.Rows.Count; i++)
                    {
                        item = (T) Activator.CreateInstance(listItemType);
                        mapRow(item, table, listItemType, i);
                        list.Add(item);
                    }
                return list;
            }
            private static void mapRow(object vOb, System.Data.DataTable table, Type type, int row)
            {
                for (int col = 0; col < table.Columns.Count; col++)
                {
                    var columnName = table.Columns[col].ColumnName;
                    var prop = type.GetProperty(columnName);
                    object data = table.Rows[row][col];
                    prop.SetValue(vOb, data, null);
                }
            }
    }

    use:

    DataTable tb;
    ...
    var list = tb.toList<MyObject>();


    Wednesday, December 09, 2009 5:06 PM