简体   繁体   中英

How to improve this LINQ query for search

Can I improve this LINQ query

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; (the ToUpper() etc being relatively expensive); 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. If this is actually an expensive property to query, you can use let to minimise the calls:

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. 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

this is multiple choice for filling or not filling textbox , but this answer is work when :
you are one field filling or two field filling or .. 7th field filling .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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