开发者

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.Tex开发者_Go百科t)) 
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 .

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜