简体   繁体   English

如何改进此LINQ查询以进行搜索

[英]How to improve this LINQ query for search

Can I improve this LINQ query 我可以改进这个LINQ查询吗?

var filter = from Dep in deptlist
where (Dep.DepNm.StartsWith(txt1.Text.ToLower()) 
  || Dep.DepNm.StartsWith(txt1.Text.ToUpper())
  ||Dep.DepNm.Contains(txt1.Text)) 
select Dep;

Currently, you do a .Text , .Text.ToUpper() and .Text.ToLower() of the fixed value per item; 目前,您为每个项目执行固定值.Text.Text.ToUpper().Text.ToLower() ; (the ToUpper() etc being relatively expensive); ToUpper()等相对昂贵); you can lift this out: 你可以解除这个:

string text = txt1.Text, upper = text.ToUpper(), lower = text.ToLower();
var filter = from Dep in deptlist
             where Dep.DepNm.StartsWith(lower) || Dep.DepNm.StartsWith(upper)
                   || Dep.DepNm.Contains(text)) 
             select Dep;

I'm assuming here that .DepNm is trivially cheap. 我在这里假设 .DepNm非常便宜。 If this is actually an expensive property to query, you can use let to minimise the calls: 如果这实际上是一个昂贵的查询属性,您可以使用let来最小化调用:

var filter = from Dep in deptlist
             let name = Dep.DepNm
             where name.StartsWith(lower) || name.StartsWith(upper)
                   || name.Contains(text)) 
             select Dep;
var filter = from Dep in deptlist
where Dep.where(d => d.DepNm.ToUpper().Conatins(txt1.Text.ToUpper())) 
select Dep;

If it's possible in your solution, add lambda expressions. 如果在您的解决方案中可以,则添加lambda表达式。 So you saved at least one line :) 所以你至少保存了一行:)


EDIT: Forget what I was saying, this is MUCH shorter: 编辑:忘掉我说的话,这要短得多:

var filter = deptlist.where(d => d.DepNm.ToUpper().Conatins(txt1.Text.ToUpper())).ToList();

I think it's faster because there is less conditions. 我认为它更快,因为条件较少。

var filter = from Dep in deptlist
where (Dep.DepNm.StartsWith(txt1.Text, StringComparison.OrdinalIgnoreCase))
||Dep.where(d => d.DepNm.ToUpper().Contains(txt1.Text.ToUpper()))
select Dep;

answer is good , i refer viewing this link that relation with search and improvement use query linq in search with empty field 答案是好的,我参考这个链接与搜索和改进的关系使用查询linq搜索空字段

this is multiple choice for filling or not filling textbox , but this answer is work when : 这是填充或不填充textbox多种选择,但这个答案适用于:
you are one field filling or two field filling or .. 7th field filling . 你是一个田间填充或两个现场填充或..第7场填充。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM