convert linq query results to datatable C#

前端 未结 3 397
无人及你
无人及你 2020-12-21 05:06

I want to convert the linq query results to datatable so that I can assign datatable to GridView to show it on asp page.

However I am not able to convert the results

3条回答
  •  长情又很酷
    2020-12-21 05:34

    You should get DataTableExtensions.CopyToDataTable

    Remove ToList().

    CopyToDataTable is an IEnumerable extension (unfortunately).

    There is a solution with custom CopyToDataTable extension method below.

    var gradeData = (from data in oAngieCtxt.prc_ShopInstanceCustomersData(
                     Convert.ToInt32(this.ShopInstanceID), 10000, false)
                    .Where( row => row.RecievedPoints != "n/a" )
                    .GroupBy(row => new { row.Name })
                    .Select(g => new
                    {
                        Name = g.Key.Name,
                        TotalPoints = g.Sum(x => Convert.ToDouble(x.RecievedPoints) 
                        * (x.Weightage.ToString() == "0.00" ? 1 
                          : Convert.ToDouble(x.Weightage)))
                    })
                     select data);
    
    var dt = gradeData.CopyToDataTable();
    

    Edit:

    Here is a more useful implementation of CopyToDataTable There is no type constraint to DataRow.

      public static class DataSetLinqOperators
      {
        public static DataTable CopyToDataTable(this IEnumerable source)
        {
            //you find the ObjectShredder implementation on the blog wich was linked.
            return new ObjectShredder().Shred(source, null, null);
        }
    
        public static DataTable CopyToDataTable(this IEnumerable source, 
                                         DataTable table, LoadOption? options)
        {
            return new ObjectShredder().Shred(source, table, options);
        }
    
      }
    

提交回复
热议问题