加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 列出DataView

发布时间:2020-12-15 06:56:08 所属栏目:百科 来源:网络整理
导读:如何将List转换为.Net中的dataview. 解决方法 我的建议是将列表转换为DataTable,然后使用表的默认视图构建您的DataView. 首先,你必须建立数据表: // T is the type of data in the list.// If you have a Listint,for example,then call this as follows://
如何将List转换为.Net中的dataview.

解决方法

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读