C# 使用LinQ to SQL返回表
我有一个名为UniversalClientSearch的搜索方法,它位于datahandler类中。该方法根据列以及在该列中搜索的内容搜索表中的数据,然后该方法必须返回一个表变量,以便在我的一个窗体上的datagridview中使用 我创建了一个LinQ to SQL语句来获取所需的数据行,并保存在var ReturnSearchQuery中,但我不知道如何将该查询转换为Table变量,tablename为tbclientC# 使用LinQ to SQL返回表,c#,sql-server,linq-to-sql,C#,Sql Server,Linq To Sql,我有一个名为UniversalClientSearch的搜索方法,它位于datahandler类中。该方法根据列以及在该列中搜索的内容搜索表中的数据,然后该方法必须返回一个表变量,以便在我的一个窗体上的datagridview中使用 我创建了一个LinQ to SQL语句来获取所需的数据行,并保存在var ReturnSearchQuery中,但我不知道如何将该查询转换为Table变量,tablename为tbclient //Fields private Dat
//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;
}
代码中的ReturnSearchQuery具有IQueryable类型:
最后,您可以使用.DataSource将客户机列表绑定到DataGridView:
谢谢,我会把它纳入我的项目!我找到了一个解决方法,但无法得到答案,那就是将UniversalClientSearch方法的返回类型更改为dynamic,然后只返回ReturnSearchQuery。
// The SQL query isn't run yet
IQueryable<tbClient> ReturnSearchQuery = from Clients in db.tbClients
where <some condition>
select Clients;
// Convert the IQueryable to a list. Here, the SQL query is run.
List<tbClient> clients = ReturnSearchQuery.ToList();
var d = new DataGridView();
d.DataSource = clients;