12

How to convert List to a dataview in .Net.

MAC
  • 6,277
  • 19
  • 66
  • 111
  • A more object orientated way than the accepted answer would be to use a method similar to answers to this question. [Sort a List using query expressions](http://stackoverflow.com/questions/695906/sort-a-listt-using-query-expressions) This is assuming that the only reason you'd want a list to be a dataview is for the sorting functionality. – Amicable Apr 08 '14 at 09:46

1 Answers1

23

My suggestion would be to convert the list into a DataTable, and then use the table's default view to build your DataView.

First, you must build the data table:

// <T> is the type of data in the list.
// If you have a List<int>, for example, then call this as follows:
// List<int> ListOfInt;
// DataTable ListTable = BuildDataTable<int>(ListOfInt);
public static DataTable BuildDataTable<T>(IList<T> lst)
{
  //create DataTable Structure
  DataTable tbl = CreateTable<T>();
  Type entType = typeof(T);
  PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entType);
  //get the list item and add into the list
  foreach (T item in lst)
  {
    DataRow row = tbl.NewRow();
    foreach (PropertyDescriptor prop in properties)
    {
      row[prop.Name] = prop.GetValue(item);
    }
    tbl.Rows.Add(row);
  }
  return tbl;
}

private static DataTable CreateTable<T>()
{
  //T –> ClassName
  Type entType = typeof(T);
  //set the datatable name as class name
  DataTable tbl = new DataTable(entType.Name);
  //get the property list
  PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entType);
  foreach (PropertyDescriptor prop in properties)
  {
    //add property as column
    tbl.Columns.Add(prop.Name, prop.PropertyType);
  }
  return tbl;
}

Next, get the DataTable's default view:

DataView NewView = MyDataTable.DefaultView;

A complete example would be as follows:

List<int> ListOfInt = new List<int>();
// populate list
DataTable ListAsDataTable = BuildDataTable<int>(ListOfInt);
DataView ListAsDataView = ListAsDataTable.DefaultView;
Koks_rs
  • 619
  • 1
  • 7
  • 25
JeffFerguson
  • 2,952
  • 19
  • 28