简体   繁体   English

c#如何从数据表中构建自定义数据视图?

[英]c# How to build a custom DataView from a DataTable?

I need to create a DataView from a DataTable, but with an unusual twist: 我需要从DataTable创建一个DataView,但是有一个不寻常的变化:

I need to decide (with code) on a row-by-row basis which rows in the DataTable are included in the DataView. 我需要逐行决定(使用代码)DataView中的哪些行包含在DataView中。

DataTable dt = LoadData();
DataView dv = new DataView(dt);

foreach (DataRow row in dt.Rows)
{
    if (RowIsGood(row))
    { 
        // This obviously doesn't work but I need equivalent logic:
        DataRowView drv = new DataRowView();
        drv.Row = row;
        dv.Add(drv);
    }
}

Some important things to note: 需要注意的一些重要事项:

  1. The code in the RowIsGood function above is too complicated to replicate using the standard RowFilter method. 上面RowIsGood函数中的代码太复杂,无法使用标准RowFilter方法进行复制。
  2. The DataTable has the potential to be very large. DataTable的潜力可能很大。 It is also referenced by multiple grid controls. 多个网格控件也引用了它。 Adding temporary columns to the DataTable to facilitate a RowFilter operation is not possible. 无法将临时列添加到DataTable中以促进RowFilter操作。
  3. I'm using .NET v4.0. 我正在使用.NET v4.0。

Is then even possible with the DataTable/DataView architecture? 那么使用DataTable / DataView体系结构,甚至可能吗?

Does LINQ allow me to customize a DataView like I need? LINQ是否允许我根据需要自定义DataView?

Thanks in advance! 提前致谢!

Since you are looking for a row by row solution and already have a function that takes a DataRow and returns a bool. 由于您正在寻找逐行解决方案,并且已经具有接受DataRow并返回布尔值的函数。

Simply add the refernce to System.Data.DataSetExtensions And use the AsDataView Method 只需将AsDataView添加到System.Data.DataSetExtensions并使用AsDataView方法

DataView dv=DT.AsEnumerable().Where(RowIsGood).AsDataView();
DataView dv = (from n in DT.AsEnumerable() Where RowIsGood(n) select n ).AsDataView();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM