Home > database >  C# Not able to use CopyToDataTable() function when grouping fields by LINQ & Datatable
C# Not able to use CopyToDataTable() function when grouping fields by LINQ & Datatable

Time:04-21

Here i am grouping data by LINQ on datatable but i was trying to use CopyToDataTable() which was not available at my side. please see my code and tell me what i missed in my code for which CopyToDataTable() not available.

 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();

Thanks

CodePudding user response:

CopyToDataTable works with DataRow which is why you can not use it.

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

Since you have IEnumerable<PeriodDto>, you can create your own extension method, see: 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;        
}

CodePudding user response:

Without using a generic extension method and using the PeriodDto definition as Expected DataRow definition

        DataTable perioddata = ds.Tables[1].AsEnumerable()
               .GroupBy(a => new
               {
                   NewPeriod = a.Field<string>("NewPeriod").ToString(),
                   PeriodOrder = a.Field<int>("PeriodOrder")
               })
               .Select(b => { 
                   DataRow row = ds.Tables[1].NewRow();
                   row["NewPeriod"] = b.Key.NewPeriod;
                   row["PeriodOrder"] = b.Key.PeriodOrder;
                   return row;
               }).CopyToDataTable();
  • Related