08-20-2017, 05:26 AM
برای تبدیل کوئری Query دریافتی از LINQ به DATATABLE میتوانید از متد زیر استفاده کنید. مزیت این متد در این است که نیازی به ایجاد کلاسهای اضافی ندارید.
Convert Linq Query To Datatable
روش استفاده :
Convert Linq Query To Datatable
کد:
public DataTable LINQResultToDataTable<T>(IEnumerable<T> Linqlist)
{
DataTable dt = new DataTable();
PropertyInfo[] columns = null;
if (Linqlist == null) return dt;
foreach (T Record in Linqlist)
{
if (columns == null)
{
columns = ((Type)Record.GetType()).GetProperties();
foreach (PropertyInfo GetProperty in columns)
{
Type colType = GetProperty.PropertyType;
if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition()
== typeof(Nullable<>)))
{
colType = colType.GetGenericArguments()[0];
}
dt.Columns.Add(new DataColumn(GetProperty.Name, colType));
}
}
DataRow dr = dt.NewRow();
foreach (PropertyInfo pinfo in columns)
{
dr[pinfo.Name] = pinfo.GetValue(Record, null) == null ? DBNull.Value : pinfo.GetValue
(Record, null);
}
dt.Rows.Add(dr);
}
return dt;
}
روش استفاده :
کد:
DAL.Lsc_WaReportsDataContext db1 = new DAL.Lsc_WaReportsDataContext();
var Query = (from row in db1.XtblTotalMelkForGrds select row);
DataTable dt2 = LINQResultToDataTable(Query);
Dg_Assets.DataSource = dt2;