2

Here I am grouping data by LINQ on DataTable but I was trying to use CopyToDataTable() which was not available on 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();
Selim Yildiz
  • 5,254
  • 6
  • 18
  • 28

2 Answers2

2

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;        
}
Selim Yildiz
  • 5,254
  • 6
  • 18
  • 28
  • 1
    without using any extension method how could i restructure my code where i can use CopyToDataTable() function ? you can remove `new PeriodDto` this class. – Ramesh Dutta Apr 21 '22 at 08:23
1

Without using a generic extension method and using the PeriodDto definition as the 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();
Selim Yildiz
  • 5,254
  • 6
  • 18
  • 28
J.Salas
  • 1,268
  • 1
  • 8
  • 15