我正在使用LINQ查询从链接的实体框架表中获取数据。如何获取存储结果的变量并创建数据表?
在下面的代码中,如何创建包含变量empInfo
的所有结果的数据表?
var empInfo = (from import in db.HmspreadsheetImports
join hpp in db.Hppings on import.VText equals hpp.HAu
where import.importDT >= DateTIme.Parse(currDate)
select new Label {
LastName = hpp.lastname,
FirstName = hpp.firstname,
Address1 = hpp.Address1,
City = import.city,
State = import.state
}).ToList();
答案 0 :(得分:1)
您可以使用此扩展方法将IList
转换为DataTable
:
public static DataTable ToDataTable<T>(this IList<T> data)
{
PropertyDescriptorCollection props =
TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable("Results");
for (int i = 0; i < props.Count; i++)
{
PropertyDescriptor prop = props[i];
table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
}
object[] values = new object[props.Count];
foreach (T item in data)
{
for (int i = 0; i < values.Length; i++)
{
values[i] = props[i].GetValue(item);
}
table.Rows.Add(values);
}
return table;
}
然后像这样实现:
DataTable dtempInfo = empInfo.ToDataTable<Label>();
答案 1 :(得分:0)
MoreLINQ可通过NuGet package获得,并提供一种ToDataTable扩展方法,
将序列中的元素追加为给定(或新)对象(DataTable)的行,并带有一组lambda表达式,用于指定其中的哪些成员(属性或字段)序列中的每个元素都将提供列值。