【问题标题】:Convert IEnumerable<DataRow> to EnumerableRowCollection<DataRow> or DataView将 IEnumerable<DataRow> 转换为 EnumerableRowCollection<DataRow> 或 DataView
【发布时间】:2015-08-27 14:08:11
【问题描述】:

我如何将result 转为EnumerableRowCollection&lt;DataRow&gt;DataView

DataTable table1 = /*something*/ ;
DataTable table2 = /*something*/ ;
DataTable table3 = /*something*/ ;

IEnumerable<DataRow> result = (from t1 in table1.AsEnumerable() join 
                                    t2 in table2.AsEnumerable() on t1.Field<int>("id") equals t2.Field<int>("t1id") join
                                    t3 in table3.AsEnumerable() on t2.Field<int>("t3id") equals t3.Field<int>("id")
                               where 666.Equals(t3.Field<int>("id"))
                              select t1);

谢谢

【问题讨论】:

  • 您可以使用CopyToDataTable 并从那里开始...
  • 无法直接实例化 EnumerableRowCollection&lt;TRow&gt;,因为该类 (docs) 没有公共构造函数。
  • 但是(from t1 in table1.AsEnumerable() where 666.Equals(t1.Field&lt;int&gt;("id")) select t1) 返回EnumerableRowCollection&lt;TRow&gt;
  • to Jon Skeet: table1,table2,table3 可以修改。我不想经常监控更改并再次执行代码...

标签: c# .net linq


【解决方案1】:

正如乔恩·斯基特所说:

DataTable table1 = /*something*/ ;
DataTable table2 = /*something*/ ;
DataTable table3 = /*something*/ ;

DataTable result = (from t1 in table1.AsEnumerable() join 
                                    t2 in table2.AsEnumerable() on t1.Field<int>("id") equals t2.Field<int>("t1id") join
                                    t3 in table3.AsEnumerable() on t2.Field<int>("t3id") equals t3.Field<int>("id")
                               where 666.Equals(t3.Field<int>("id"))
                              select t1).CopyToDataTable<DataRow>();

如果你想要一个数据视图:

DataTable table1 = /*something*/ ;
DataTable table2 = /*something*/ ;
DataTable table3 = /*something*/ ;

DataView result = (from t1 in table1.AsEnumerable() join 
                                    t2 in table2.AsEnumerable() on t1.Field<int>("id") equals t2.Field<int>("t1id") join
                                    t3 in table3.AsEnumerable() on t2.Field<int>("t3id") equals t3.Field<int>("id")
                               where 666.Equals(t3.Field<int>("id"))
                              select t1).CopyToDataTable<DataRow>().AsDataView();

【讨论】:

  • 还有一个问题... 如果result.count == 0 那么异常.. :((
  • 不幸的是,每次更改 t2 时我都会更新 DataView :(
【解决方案2】:

来自 .NET 文档here

DataTable orders = dataSet.Tables["SalesOrderHeader"];

EnumerableRowCollection<DataRow> query =
    from order in orders.AsEnumerable()
    where order.Field<bool>("OnlineOrderFlag") == true
    orderby order.Field<decimal>("TotalDue")
    select order;

DataView view = query.AsDataView();

bindingSource1.DataSource = view;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多