根据Linq查询创建数据表 我使用Ling在dataGridview上显示我的数据,并且使用linq搜索功能搜索人。它可以正常工作,但不如Datatable那样。我必须在Serch函数将其命名之前给孔名称写上名字。我想从Linq查询创建Creat DataTable,但是我不知道该怎么做。 这是我的代码:
public void SerachdataEmp(string name)
{
db = new EmployeeEntity();
var result = (from u in db.Employee
join d in db.Department on u.DepartmentId equals d.DepartmentId
where u.FirstName == name
select new
{
FirstName = u.FirstName,
LastName = u.LastNameName,
DepartmentName = d.DepartmentName
}
}).Tolist();
dataGridView1.DataSource = result;
我尝试过这样
(from u in db.Employee.AsEnumerable()
join d in db.Department.AsEnumerable() on u.DepartmentId equals d.DepartmentId
where u.FirstName == searchEmployee
but then I don't know how to do. Thank you in advance!
答案 0 :(得分:0)
代替使用query.ToList();
使用
query.CopyToDataTable();
答案 1 :(得分:0)
我不建议您这样做,并且我不认为您的搜索问题是不使用DataTable
,但是使用这些扩展名,您可以将查询答案转换为DataTable
-只需输入ToDataTable()
代替ToList()
。
public static class ExtensionMethods {
// ***
// *** IEnumerable<> Extensions
// ***
public static DataTable ToDataTable<T>(this IEnumerable<T> rows) {
var dt = new DataTable();
if (rows.Any()) {
var rowType = typeof(T);
var memberInfos = rowType.GetPropertiesOrFields();
foreach (var info in memberInfos)
dt.Columns.Add(new DataColumn(info.Name, info.GetMemberType()));
foreach (var r in rows)
dt.Rows.Add(memberInfos.Select(i => i.GetValue(r)).ToArray());
}
return dt;
}
// ***
// *** MemberInfo Extensions
// ***
public static Type GetMemberType(this MemberInfo member) {
switch (member) {
case FieldInfo mfi:
return mfi.FieldType;
case PropertyInfo mpi:
return mpi.PropertyType;
case EventInfo mei:
return mei.EventHandlerType;
default:
throw new ArgumentException("MemberInfo must be if type FieldInfo, PropertyInfo or EventInfo", nameof(member));
}
}
public static object GetValue(this MemberInfo member, object srcObject) {
switch (member) {
case FieldInfo mfi:
return mfi.GetValue(srcObject);
case PropertyInfo mpi:
return mpi.GetValue(srcObject);
default:
throw new ArgumentException("MemberInfo must be of type FieldInfo or PropertyInfo", nameof(member));
}
}
// ***
// *** Type Extensions
// ***
public static List<MemberInfo> GetPropertiesOrFields(this Type t, BindingFlags bf = BindingFlags.Public | BindingFlags.Instance) =>
t.GetMembers(bf).Where(mi => mi.MemberType == MemberTypes.Field | mi.MemberType == MemberTypes.Property).ToList();
}