Click here to Skip to main content
15,916,846 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I am having a linq select query I want to copy that result to a datatable. In this the copytoDataTable is not coming. I am selecting the column value from the grdiview which is selected by using the linq query. How to copy this one to Datatable.

C#
var result = (from GridViewRow msgRow in grdPrice.Rows
                    let ReferenceNO = ((HiddenField)msgRow.FindControl("hfReferenceNo")).Value
                    where ((CheckBox)msgRow.FindControl("chkSelect")).Checked
                     select new { ReferenceNO }).ToList();

Thanks
Posted

Your result is a List (since you called ToList on the IEnumerable) - so you can use this: Converting a List to a DataTable[^].
If it wasn't, then you'd have to change the code in the Tip a small amount to make it IEnumerable<T> instead of IList<T>
 
Share this answer
 
Try This

C#
public static class HelperFunctions
   {
       public static void Map<T>(this IEnumerable<T> source, Action<T> func)
       {
           foreach (T i in source)
               func(i);
       }

       public static DataTable ToDataTable<T>(this IEnumerable<T> source)
       {
           var dt = new DataTable();
           var properties = typeof(T).GetProperties();
           dt.Columns.AddRange(properties.Select(x => new DataColumn(x.Name, x.PropertyType)).ToArray());
           source.Select(x => dt.NewRow().ItemArray = properties.Select(y => y.GetValue(x, null)).ToArray()).Map(x => dt.Rows.Add(x));
           return dt;
       }
   }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900