Friday, May 4, 2012

Converting a List to C# datatable object.

While coding some times we come across situations where we need to convert the list<T> data to a data table. The below method will be handy if you need to conver an Ilist  to datatable.


public static DataTable ToDataTable<T>(this IList<T> data)
      {
          PropertyDescriptorCollection props =
              TypeDescriptor.GetProperties(typeof(T));
          DataTable table = new DataTable();
          for (int i = 0; i < props.Count; i++)
          {
              PropertyDescriptor prop = props[i];
               table.Columns.Add(prop.Name, prop.PropertyType);
          }
          object[] values = new object[props.Count];
          foreach (T item in data)
          {
               for (int i = 0; i < values.Length; i++)
              {
                  values[i] = props[i].GetValue(item);
               }
               table.Rows.Add(values);
          }
          return table;
      }

1 comment:

  1. Nice work, your blog is concept-oriented, kindly share more blogs like this
    Dot NET Online Course

    ReplyDelete