转换方法代码:
代码
private DataTable ConvertToTable(IQueryable query)
{
DataTable dtList = new DataTable();
bool isAdd = false;
PropertyInfo[] objProterties = null;
foreach (var item in query)
{
if (!isAdd)
{
objProterties = item.GetType().GetProperties();
foreach (var itemProterty in objProterties)
{
Type type = null;
if (itemProterty.PropertyType != typeof(string) && itemProterty.PropertyType != typeof(int) && itemProterty.PropertyType != typeof(DateTime))
{
type = typeof(string);
}
else
{
type = itemProterty.PropertyType;
}
dtList.Columns.Add(itemProterty.Name, type);
}
isAdd = true;
}
var row = dtList.NewRow();
foreach (var pi in objProterties)
{
row[pi.Name] = pi.GetValue(item, null);
}
dtList.Rows.Add(row);
}
return dtList;
}
{
DataTable dtList = new DataTable();
bool isAdd = false;
PropertyInfo[] objProterties = null;
foreach (var item in query)
{
if (!isAdd)
{
objProterties = item.GetType().GetProperties();
foreach (var itemProterty in objProterties)
{
Type type = null;
if (itemProterty.PropertyType != typeof(string) && itemProterty.PropertyType != typeof(int) && itemProterty.PropertyType != typeof(DateTime))
{
type = typeof(string);
}
else
{
type = itemProterty.PropertyType;
}
dtList.Columns.Add(itemProterty.Name, type);
}
isAdd = true;
}
var row = dtList.NewRow();
foreach (var pi in objProterties)
{
row[pi.Name] = pi.GetValue(item, null);
}
dtList.Rows.Add(row);
}
return dtList;
}
调用方法:
//linq查询语句
var queryData =
from dv in emcsDataContext.DailyVals
join vrb in emcsDataContext.Variables on dv.VariableID equals vrb.VariableID
where dv.VariableID == variableId && dv.CollectTime >= selectDate && dv.CollectTime < selectDate.AddDays(1)
orderby dv.CollectTime
select new
{
dv.ID,
dv.VariableID,
dv.CollectTime,
dv.VariableValue,
vrb.UpLimite,
vrb.LowLimite,
statDate = dv.CollectTime.ToShortTimeString()
};
//转换
ConvertToTable(queryData)
var queryData =
from dv in emcsDataContext.DailyVals
join vrb in emcsDataContext.Variables on dv.VariableID equals vrb.VariableID
where dv.VariableID == variableId && dv.CollectTime >= selectDate && dv.CollectTime < selectDate.AddDays(1)
orderby dv.CollectTime
select new
{
dv.ID,
dv.VariableID,
dv.CollectTime,
dv.VariableValue,
vrb.UpLimite,
vrb.LowLimite,
statDate = dv.CollectTime.ToShortTimeString()
};
//转换
ConvertToTable(queryData)