2010-10-01 81 views
10

如何将List转换为.Net中的数据视图。List <T> to DataView

+0

一更多的面向对象的方式比接受的答案是使用类似于这个问题的答案的方法。 [使用查询表达式排序列表](http://stackoverflow.com/questions/695906/sort-a-listt-using-query-expressions) 这是假设你想要列表的唯一原因是数据视图用于排序功能。 – Amicable 2014-04-08 09:46:14

回答

18

我的建议是将列表转换为DataTable,然后使用该表的默认视图来构建DataView。

首先,你必须建立数据表:

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

接下来,让DataTable的默认视图:

DataView NewView = MyDataTable.DefaultView; 

一个完整的例子如下:

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

一个较小的更正CreateTable应该也是静态的。 – user3141326 2015-01-15 07:17:04