如何提高搜索这个LINQ查询 [英] How to improve this LINQ query for search

查看:99
本文介绍了如何提高搜索这个LINQ查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以改进这个LINQ查询

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;


推荐答案

.Text , .Text.ToUpper() .Text.ToLower() 每个项目的固定值; ( ToUpper()等比较贵);你可以解决这个问题:

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;

假设这里 .DepNm 很便宜。如果这实际上是一个昂贵的查询属性,您可以使用 let 最小化调用:

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;

这篇关于如何提高搜索这个LINQ查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆