最佳实践:将LINQ查询结果转换为DataTable而无需循环

24
什么是将LINQ查询结果转换为新的 DataTable 的最佳实践?我是否可以找到比对每个结果项进行 foreach 更好的解决方案? 编辑:匿名类型
var rslt = from eisd in empsQuery
           join eng in getAllEmployees()
           on eisd.EMPLOYID.Trim() equals eng.EMPLOYID.Trim()
           select new
           {
               eisd.CompanyID,
               eisd.DIRECTID,
               eisd.EMPLOYID,
               eisd.INACTIVE,
               eisd.LEVEL,
               eng.EnglishName
           };

编辑2: 我遇到了异常:

除了Contains()运算符之外,本地序列不能在LINQ to SQL查询操作符的实现中使用。

当我尝试执行查询时,发现了解决方案,请参见IEnumerable.Except wont work, so what do I do?Need linq help

5个回答

35
使用Linq to Dataset。来自MSDN的说明:使用查询创建DataTable(LINQ to DataSet)
// Query the SalesOrderHeader table for orders placed 
// after August 8, 2001.
IEnumerable<DataRow> query =
    from order in orders.AsEnumerable()
    where order.Field<DateTime>("OrderDate") > new DateTime(2001, 8, 1)
    select order;

// Create a table from the query.
DataTable boundTable = query.CopyToDataTable<DataRow>();

如果您有匿名类型:
来自 Coder 博客:使用 Linq 匿名类型和 CopyDataTable 避免过多的数据库调用 它解释了如何使用 MSDN 的如何实现 CopyToDataTable,其中通用类型 T 不是 DataRow

1
如果查询包含 'select new {fld1, fld2, fld3}',那么它无法转换为IEnumerable? - Rami Alshareef
http://ayende.com/Blog/archive/2007/05/09/Converting-an-object-collection-to-a-DataSet.aspx - Hao

4
将查询结果转换为DataTables通用函数中的DataTable
 DataTable ddt = new DataTable();

 ddt = LINQResultToDataTable(query);

    public DataTable LINQResultToDataTable<T>(IEnumerable<T> Linqlist)
    {
        DataTable dt = new DataTable();


        PropertyInfo[] columns = null;

        if (Linqlist == null) return dt;

        foreach (T Record in Linqlist)
        {

            if (columns == null)
            {
                columns = ((Type)Record.GetType()).GetProperties();
                foreach (PropertyInfo GetProperty in columns)
                {
                    Type colType = GetProperty.PropertyType;

                    if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition()
                    == typeof(Nullable<>)))
                    {
                        colType = colType.GetGenericArguments()[0];
                    }

                    dt.Columns.Add(new DataColumn(GetProperty.Name, colType));
                }
            }

            DataRow dr = dt.NewRow();

            foreach (PropertyInfo pinfo in columns)
            {
                dr[pinfo.Name] = pinfo.GetValue(Record, null) == null ? DBNull.Value : pinfo.GetValue
                (Record, null);
            }

            dt.Rows.Add(dr);
        }
        return dt;
    }  

请添加一些解释。 - Mohit Jain

2

我在asp.net web应用程序中使用了morelinq.2.2.0包,Nuget包管理器控制台

PM> Install-Package morelinq

命名空间

using MoreLinq;

我示例存储过程 sp_Profile() 返回个人资料详情

DataTable dt = context.sp_Profile().ToDataTable();

1
使用System.Reflection并迭代查询对象中的每个记录。
Dim dtResult As New DataTable
Dim t As Type = objRow.GetType
Dim pi As PropertyInfo() = t.GetProperties()

For Each p As PropertyInfo In pi
    dtResult.Columns.Add(p.Name)
Next
Dim newRow = dtResult.NewRow()
For Each p As PropertyInfo In pi
    newRow(p.Name) = p.GetValue(objRow,Nothing)
Next
dtResult.Rows.Add(newRow.ItemArray)
Return dtResult

-1

尝试 Datatable dt= (from rec in dr.AsEnumerable() select rec).CopyToDataTable()


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接