我有一个名为" UniversalClientSearch"的搜索方法。并位于datahandler类中。该方法根据列中的数据和要在该列中搜索的内容搜索表中的数据,然后该方法必须返回一个表变量,以便在我的一个表单上的datagridview中使用。
我已经创建了一个LinQ to SQL语句来获取我想要的数据行,并保存在var ReturnSearchQuery中,但我不知道如何将该查询转换为Table的变量,表名为tbclient。
//Fields
private DataAccessDataContext db;
//Constructor
public Datahandler()
{
this.db = new DataAccessDataContext();
}
//Method
public Table<tbClient> UniversalClientSearch(string SearchType, string SearchParameter)
{
//This is just here to initialize the variable so it can be changed in the switch
var ReturnSearchQuery = from Clients in db.tbClients
select Clients;
//Filters Query based on what column to search
switch (SearchType)
{
case "Client_ID":
ReturnSearchQuery = from Clients in db.tbClients
where Clients.Client_ID == int.Parse(SearchParameter)
select Clients;
break;
case "Client_Name":
ReturnSearchQuery = from Clients in db.tbClients
where Clients.Client_Name.Contains(SearchParameter)
select Clients;
break;
case "Client_Address":
ReturnSearchQuery = from Clients in db.tbClients
where Clients.Client_Address.Contains(SearchParameter)
select Clients;
break;
case "Contact_Number":
ReturnSearchQuery = from Clients in db.tbClients
where Clients.Contact_Number.Contains(SearchParameter)
select Clients;
break;
case "Contact_Email":
ReturnSearchQuery = from Clients in db.tbClients
where Clients.Contact_Email.Contains(SearchParameter)
select Clients;
break;
case "Client_Type":
ReturnSearchQuery = from Clients in db.tbClients
where Clients.Client_Type == SearchParameter
select Clients;
break;
}
//Make new table to be returned later
Table<tbClient> ReturnClientsTable = new Table<tbClient>();
foreach (var item in ReturnSearchQuery)
{
//Query has to be converted to Table<tbClient>
}
//Table return to be used in datagridview
return ReturnClientsTable;
}
答案 0 :(得分:1)
IQueryable<tbClient>
类型为// The SQL query isn't run yet
IQueryable<tbClient> ReturnSearchQuery = from Clients in db.tbClients
where <some condition>
select Clients;
:
IQueryable
由于延迟执行,在枚举// Convert the IQueryable to a list. Here, the SQL query is run.
List<tbClient> clients = ReturnSearchQuery.ToList();
之前不会执行SQL查询。
DataGridView
最后,您可以使用.DataSource
将客户列表绑定到var d = new DataGridView();
d.DataSource = clients;
:
sanitize