列表< T>到DataView [英] List<T> to DataView
本文介绍了列表< T>到DataView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将List转换为.Net中的数据视图.
How to convert List to a dataview in .Net.
推荐答案
我的建议是将列表转换为DataTable,然后使用表的默认视图构建您的DataView.
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;
完整的示例如下:
List<int> ListOfInt = new List<int>();
// populate list
DataTable ListAsDataTable = BuildDataTable<int>(ListOfInt);
DataView ListAsDataView = ListAsDataTable.DefaultView;
这篇关于列表< T>到DataView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文