c# - List<T> 到 DataView

标签 c# list dataview

如何将 List 转换为 .Net 中的数据 View 。

最佳答案

我的建议是将列表转换为数据表,然后使用表的默认 View 来构建您的数据 View 。

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

// <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的默认 View :

DataView NewView = MyDataTable.DefaultView;

一个完整的例子如下:

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

关于c# - List<T> 到 DataView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3839022/

相关文章:

c# - 单例构造函数问题

Python 字数统计不起作用

python - 从坐标元组列表中选择最小值

python - Django 从分组列表中过滤

c# - 将 Like 语句与 DataView RowFIlter 一起使用

c# - 如何在构造函数中获取参数数量

c# - C#中的递归和匿名方法

c# - 从 DataView C# 中获取值(value)

c# 加载C文件,然后将其转换为Assembly

c# - 如何将 SQL Server 表拉入内存以便对其运行查询