【问题标题】:Return typed DataTable from Linq Query从 Linq 查询返回类型化的 DataTable
【发布时间】:2010-11-06 09:46:49
【问题描述】:

我在 XML 中有一个(断开的)类型化数据集,我在 LINQ 中查询:

var productlist = from prds in dsProducts.Products.AsEnumerable()
where (prds.Field<string>("productid").Contains(searchpattern) || 
       prds.Field<string>("productname").Contains(searchpattern))
select prds;

这个列表很好,但如果我试着说:

return (DataSetProducts.productsDataTable)productlist.Skip(begin).Take(pagesize).CopyToDataTable();

它说它不能将 System.DataTable 转换为 DataSetProducts.productsDataTable,但是它是同一个表。

关于如何返回类型化的 DataTable 有什么想法吗?

【问题讨论】:

    标签: .net linq dataset


    【解决方案1】:

    好吧,CopyToDataTable 无法知道对于给定类型的 DataRow 正确的强 DataTable 类型是什么,因为 DataRow 没有提供该信息(恕我直言)。

    也许您可以编写自己的 CopyToDataTable 方法,该方法将采用另一个类型参数来指定表类型。类似的东西:

    public static TTable CopyToDataTable<TRow, TTable>(this IEnumerable<TRow> rows)
      where TRow : DataRow, new()
      where TTable : DataTable, new()
    {
        TTable table = new TTable();
        foreach (TRow row in rows)
        {
            TRow rowCopy = new TRow();
            object[] itemArrayCopy = new object[row.ItemArray.Length];
            row.ItemArray.CopyTo(itemArrayCopy, 0);
            rowCopy.ItemArray = itemArrayCopy;
            table.Rows.Add(rowCopy);
        }
        return table;
    }
    

    编辑:

    如何在上面的例子中使用这个新功能?

    您必须将此扩展方法放在静态类中。如果您将类放在不同的命名空间中,请确保使用 using 子句将该命名空间导入范围内。

    然后您可以使用这样的方法(您必须指定类型参数,因为编译器无法推断 TTable 类型):

    return productlist.Skip(begin).Take(pagesize).CopyToDataTable<DataSetProducts.productsRow, DataSetProducts.productsDataTable>();
    

    请注意,我没有测试此代码,可能存在一些错误...

    【讨论】:

    • 非常好的解决方法,谢谢。像我这样的傻瓜有一个问题:我怎样才能在上面的例子中使用这个新功能?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-13
    • 1970-01-01
    • 2012-12-09
    • 1970-01-01
    • 2018-11-10
    • 1970-01-01
    • 2011-08-20
    相关资源
    最近更新 更多