C#从DataView创建DataView

时间:2015-08-24 21:36:38

标签: c# linq ado.net

我想通过过滤现有的DataView来创建一个新的DataView,但是我遇到了麻烦,因为DataView没有.AsEnumerable()方法,并且没有实现IEnumerable {DataRow}。

这基本上就是我想要完成的事情:

//Some table.
DataTable dt = new DataTable();

//Somewhere in here the table is given columns and rows...

//The first view shows some subset of the table.  
//(This works fine.)
DataView dv1 = dt.AsEnumerable()
    .Where(r => r.Field<int>("ID") < 1000)
    .AsDataView();

//The second view should show a subset of the first view, but I cannot find the methods to do this.
//(This does not compile.)
DataView dv2 = dv1.AsEnumerable()
    .Where(r => r.Field<int>("Salary") > 50000)
    .AsDataView();

到目前为止,我提出的最好的事情是

DataView dv2 = dv1.ToDataTable().AsEnumerable()
   .Where(r => r.Field<int>("Salary") > 50000)
   .AsDataView();

这是丑陋的,我猜测效率低下。

从视图中制作视图的最佳方法是什么?

1 个答案:

答案 0 :(得分:2)

在单独的IEnumerable中创建第一个过滤器,然后使用它来创建两个数据视图:

var filtered = dt.AsEnumerable()
                 .Where(r => r.Field<int>("ID") < 1000);


DataView dv1 = filtered.AsDataView();

DataView dv2 = filtered.Where(r => r.Field<string>("Salary") > 50000)
                       .AsDataView();