2010-10-01 14 views
10

Cómo convertir List a dataview en .Net.List <T> to DataView

+0

Un más orientado a objetos que la respuesta aceptada sería usar un método similar a las respuestas a esta pregunta. [Ordene una lista usando expresiones de consulta] (http://stackoverflow.com/questions/695906/sort-a-listt-using-query-expressions) Esto supone que la única razón por la que desea que aparezca una lista una vista de datos es para la funcionalidad de clasificación. – Amicable

Respuesta

18

Mi sugerencia sería convertir la lista en una DataTable, y luego usar la vista predeterminada de la tabla para construir su DataView.

En primer lugar, se debe construir la tabla de datos:

// <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; 
} 

A continuación, obtener vista predeterminada de la DataTable:

DataView NewView = MyDataTable.DefaultView; 

Un ejemplo completo sería la siguiente:

List<int> ListOfInt = new List<int>(); 
// populate list 
DataTable ListAsDataTable = BuildDataTable<int>(ListOfInt); 
DataView ListAsDataView = ListAsDataTable.DefaultView; 
+1

Una corrección menor CreateTable también debería ser estática. – user3141326