How to convert LINQ result to DATATABLE?

Is there a way to convert the result of a LINQ expression to a DataTable without going through each element?

+3
source share
2 answers

There is no way to create it without stepping through each element. The Linq expression is computed as needed, so it will go through each line (for matching and selection).

I think you should try instead of DataTable.Select() ( MSDN link ), since it returns an array of DataRow objects that you can add the following to a new table:

 var rows = [ORIGINAL DATA TABLE].Select("id>5"); var dtb=[ORIGINAL DATA TABLE].Clone(); foreach(DataRow r in rows) { var newRow = dtb.NewRow(); newRow.ItemArray = r.ItemArray; dtb.Rows.Add(newRow);//I'm doubtful if you need to call this or not } 
+2
source

Credit for this blogger , but I improved his algorithm here. Make yourself an extension method:

  public static DataTable ToADOTable<T>(this IEnumerable<T> varlist) { DataTable dtReturn = new DataTable(); // Use reflection to get property names, to create table // column names PropertyInfo[] oProps = typeof(T).GetProperties(); foreach (PropertyInfo pi in oProps) { Type colType = pi.PropertyType; if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>))) colType = colType.GetGenericArguments()[0]; dtReturn.Columns.Add(new DataColumn(pi.Name, colType)); } foreach (T rec in varlist) { DataRow dr = dtReturn.NewRow(); foreach (PropertyInfo pi in oProps) dr[pi.Name] = pi.GetValue(rec, null) == null ? DBNull.Value : pi.GetValue(rec, null); dtReturn.Rows.Add(dr); } return (dtReturn); } 

Using:

 DataTable dt = query.ToADOTable(); 
+5
source

Source: https://habr.com/ru/post/918696/


All Articles