2010-10-01 13 views
10

Come convertire List in un dataview in .Net.Elenco <T> in DataView

+0

A un modo più orientato agli oggetti rispetto alla risposta accettata sarebbe utilizzare un metodo simile alle risposte a questa domanda. [Ordina un elenco utilizzando le espressioni di query] (http://stackoverflow.com/questions/695906/sort-a-listt-using-query-expressions) Questo presume che l'unica ragione per cui desideri sia un elenco un dataview è per la funzionalità di ordinamento. – Amicable

risposta

18

Il mio suggerimento sarebbe quello di convertire l'elenco in un DataTable e quindi utilizzare la vista predefinita della tabella per creare il tuo DataView.

In primo luogo, è necessario costruire la tabella di dati:

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

Avanti, ottenere visualizzazione predefinita del DataTable:

DataView NewView = MyDataTable.DefaultView; 

Un esempio completo potrebbe essere il seguente:

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

Anche una correzione minore CreateTable dovrebbe essere statica. – user3141326

Problemi correlati