C# 按 LINQ 和 Datatable 对字段进行分组时无法使用 CopyToDataTable() 函数

标签 c# linq

在这里,我通过 LINQ 在 DataTable 上对数据进行分组,但我尝试使用 CopyToDataTable(),但我这边不可用。请查看我的代码并告诉我代码中缺少哪些 CopyToDataTable() 不可用的内容。

DataTable perioddata = ds.Tables[1].AsEnumerable()
     .GroupBy(a => new
     {
        NewPeriod = a.Field<string?>("NewPeriod").ToString(),
        PeriodOrder = a.Field<int>("PeriodOrder").ToString().ToInt32()
     })
     .Select(b => new PeriodDto
     {
        NewPeriod = b.Key.NewPeriod,
        PeriodOrder = b.Key.PeriodOrder
     }).CopyToDataTable();

最佳答案

CopyToDataTableDataRow一起工作这就是为什么你不能使用它。

DataTable CopyToDataTable<T>(this IEnumerable<T> source) where T : DataRow

既然你有IEnumerable<PeriodDto> ,您可以创建自己的扩展方法,参见:Convert generic List/Enumerable to DataTable?

public static DataTable ToDataTable<T>(this IList<T> data)
{
    PropertyDescriptorCollection props =
        TypeDescriptor.GetProperties(typeof(T));
    DataTable table = new DataTable();
    for(int i = 0 ; i < props.Count ; i++)
    {
        PropertyDescriptor prop = props[i];
        table.Columns.Add(prop.Name, prop.PropertyType);
    }
    object[] values = new object[props.Count];
    foreach (T item in data)
    {
        for (int i = 0; i < values.Length; i++)
        {
            values[i] = props[i].GetValue(item);
        }
        table.Rows.Add(values);
    }
    return table;        
}

关于C# 按 LINQ 和 Datatable 对字段进行分组时无法使用 CopyToDataTable() 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71949530/

相关文章:

c# - 在 XAML WPF 中为 ListView 项设置工具提示

c# - 如何使用 Microsoft.Azure.ActiveDirectory.GraphClient 删除 AzureAD 中的用户管理器

c# - 将嵌套循环重构为单个 LINQ 查询

c# linq to xml 列表

c# - 对列表进行分组 - 寻找更好的方法

c# - Xamarin Studio 未启动 iOS 项目。错误 MT1108 : Could not find developer tools for this 10. 0.2 设备

c# - 防止类具有在 C# 中创建的静态实例

c# - ASP.NET C# : Which Design Pattern should I use and why?

c# - Max,SelectMany,可能没有响应

c# - LINQ执行流程(作业)