将List<T>转换为DataView。

12

如何在 .Net 中将 List 转换为 DataView。


一个比被接受的答案更面向对象的方法是使用类似于这个问题答案的方法。使用查询表达式对List<T>进行排序 这是假设你想要将列表作为数据视图的唯一原因是为了排序功能。 - Amicable
1个回答

23

我的建议是将列表转换为一个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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接