C#仅在编辑文本框时查询
我有一个查询,可以处理一个很棒的数据表。查询代码为:C#仅在编辑文本框时查询,c#,C#,我有一个查询,可以处理一个很棒的数据表。查询代码为: var getExtInv = snd.external_invoices.OrderByDescending(x => x.date).ToList(); var query = (from c in getExtInv join o in snd.invoices on c.idexternal_invoices equals o.id_external_invoice selec
var getExtInv = snd.external_invoices.OrderByDescending(x => x.date).ToList();
var query = (from c in getExtInv
join o in snd.invoices on c.idexternal_invoices equals o.id_external_invoice
select new {c.idexternal_invoices,
c.businessname,
o.number,
c.message,
c.price,
c.date,
c.tipologiaPagamento,
c.esitoPagamento,
c.iduser
}).ToList();
我需要用一些可以为空的文本框值来过滤这个查询。一个搜索筛选器的示例如下:
if (txtIdUser.Text != "")
{
int idUserSel = Convert.ToInt32(txtIdUser.Text);
query = query.Where(x => x.iduser == idUserSel).ToList();
}
问题在于,这种方法最初加载的数据量非常大,然后根据是否填充文本字段进行过滤。这样做时,初始加载时间非常长。我怎样才能加快这个过程
感谢前面提到的所有,在准备使用结果之前,不要使用
.ToList
、.ToArray
、.Count
等
int i = 0;
var query = from c in snd.external_invoices.OrderByDescending(x => x.date)
join o in snd.invoices on c.idexternal_invoices equals o.id_external_invoice
select new {c.idexternal_invoices, c.businessname, o.number, c.message,
c.price, c.date, c.tipologiaPagamento, c.esitoPagamento, c.iduser };
if(int.TryParse(txtIdUser.Text, out i) // this will check if text is not empty and valid int
query = query.Where(x => x.iduser == i);
最后,当您准备好使用结果时:
var results = query.ToList();
停止调用ToList()
,因为这会将所有数据放入内存,导致以后的查询也在内存中运行(而不是在数据库中)。只需在最后有一个ToList()
。