最佳实践:将LINQ查询结果转换为DataTable而不进行循环

时间:2010-12-16 12:17:08

标签: c# linq-to-sql datatable

将LINQ-Query结果转换为新DataTable的最佳做法是什么? 我可以找到比foreach每个结果项更好的解决方案吗?

修改  AnonymousType

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 个答案:

答案 0 :(得分:31)

使用Linq数据集。来自MSDN:Creating a DataTable From a Query (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>();

如果你有匿名类型:

来自编码器博客:Using Linq anonymous types and CopyDataTable

它解释了如何使用MSDN的How to: Implement CopyToDataTable Where the Generic Type T Is Not a DataRow

答案 1 :(得分:2)

在DataTables通用函数中转换查询结果

 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;
    }  

答案 2 :(得分: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

答案 3 :(得分:1)

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

PM> Install-Package morelinq

命名空间

using MoreLinq;

我的示例存储过程sp_Profile()返回配置文件详细信息

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

答案 4 :(得分:0)

尝试 数据表dt =(从dr.AsEnumerable()的rec中选择rec)。CopyToDataTable()