You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将LINQ查询结果写入DataTable?已尝试CopyToDataTable()

将LINQ匿名类型查询结果写入DataTable的解决方案

问题原因

你使用的CopyToDataTable()方法仅支持实现DataRow接口的对象集合,而你的LINQ查询返回的是匿名类型的集合,因此无法直接调用该方法。

解决方案一:手动创建并填充DataTable

适合字段较少的场景,操作直观可控:

1. 修正LINQ查询(避免空引用异常)

由于是左连接,subCities可能为null,需先判断再取值:

var result = from clients in Clients_dt.AsEnumerable()
             join cities in Cities_dt.AsEnumerable()
                  on clients.Field<int>("CityId") equals cities.Field<int>("ID") into ClientCityGroup
             from subCities in ClientCityGroup.DefaultIfEmpty()
             select new 
                    {
                        Name = clients.Field<string>("Name"),
                        City = subCities != null ? subCities.Field<string>("Name") : null
                    };

2. 手动构建DataTable并填充数据

// 初始化DataTable并定义列
DataTable resultDataTable = new DataTable();
resultDataTable.Columns.Add("Name", typeof(string));
resultDataTable.Columns.Add("City", typeof(string));

// 遍历查询结果,逐行添加到DataTable
foreach (var item in result)
{
    DataRow newRow = resultDataTable.NewRow();
    newRow["Name"] = item.Name;
    // 处理空值,避免DBNull兼容性问题
    newRow["City"] = item.City ?? DBNull.Value;
    resultDataTable.Rows.Add(newRow);
}

解决方案二:通用扩展方法(支持任意匿名/实体类型)

适合频繁处理这类场景,通过反射自动生成DataTable:

定义扩展方法

public static class EnumerableExtensions
{
    public static DataTable CopyToDataTable<T>(this IEnumerable<T> source)
    {
        if (source == null) throw new ArgumentNullException(nameof(source));
        
        DataTable dataTable = new DataTable();
        PropertyInfo[] properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
        
        // 根据类型属性自动创建DataTable列
        foreach (PropertyInfo prop in properties)
        {
            // 处理可空类型,获取基础类型
            Type columnType = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType;
            dataTable.Columns.Add(prop.Name, columnType);
        }
        
        // 遍历数据源填充数据行
        foreach (T item in source)
        {
            DataRow row = dataTable.NewRow();
            foreach (PropertyInfo prop in properties)
            {
                object value = prop.GetValue(item, null);
                row[prop.Name] = value ?? DBNull.Value;
            }
            dataTable.Rows.Add(row);
        }
        
        return dataTable;
    }
}

使用扩展方法

修正LINQ查询后,直接调用扩展方法即可:

var resultDataTable = result.CopyToDataTable();

内容的提问来源于stack exchange,提问作者sereganator

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 15:52:18