c# – 列出DataView

如何将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;

相关文章

原文地址:http://msdn.microsoft.com/en-us/magazine/cc163...
前言 随着近些年微服务的流行,有越来越多的开发者和团队所采...
最近因为比较忙,好久没有写博客了,这篇主要给大家分享一下...
在多核CPU在今天和不久的将来,计算机将拥有更多的内核,Mic...
c语言输入成绩怎么判断等级
字符型数据在内存中的存储形式是什么