Linq查询需要时间 [英] Linq query taking time

查看:85
本文介绍了Linq查询需要时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以建议我为什么我的linq查询需要时间



Can anyone please suggest me why my linq query taking time

lstSearch = (From s In lstGetResult
     Where (s.CODE.StartsWith(txtCode.Text.Trim(), StringComparison.OrdinalIgnoreCase)) OrElse
     (s.NAME.StartsWith(txtCode.Text.Trim(), StringComparison.OrdinalIgnoreCase))
     Select New SPGet_Result With {.CODE = s.CODE, .NAME = s.NAME}).ToList()





提前致谢:)



Thanks in advance :)

推荐答案

尝试拆分查询以找到最慢的部分。



注意:首先,我认为记住,很慢,可能是它包含甚至索引更快,结果是你搜索整个部分,而不是开始,所以撕裂ering可能会慢一点,如果你不想这样,你可以在你的txtCode和CODE / NAME的子串(0,长度)之间进行等于比较,并测试是否比statswith更快。





try to split the query to find the slowest part.

Note : the startswith, i think to remember, is quite slow, may be its faster a contains or even a indexof, the result is that you search the whole part, not the begining, so the rendering could be slower, if you don''t want that, you can make a "equals" comparison between your txtCode and a substring(0, length) of the CODE/NAME, and test if is faster than statswith.


var stopWatch = new System.Diagnostics.Stopwatch();
stopWatch.Start();

var tempLstSearch = lstGetResult;
var txtCode = txtCode.Text.Trim();

stopWatch.Stop();
var ts1 = stopWatch.Elapsed;

if(txtCode.Length > 0)
{
   tempLstSearch = tempLstSearch.Where(i=> (
                                             (i.CODE.IndexOf(txtCode,System.StringComparison.CurrentCultureIgnoreCase) >= 0) 
                                             ||
                                             (i.NAME.IndexOf(txtCode,System.StringComparison.CurrentCultureIgnoreCase) >= 0)
                                            ));
   stopWatch.Stop();
   var ts2 = stopWatch.Elapsed;
}

var search =  From s In tempLstSearch 
              Select New SPGet_Result With {.CODE = s.CODE, .NAME = s.NAME};

stopWatch.Stop();
varts3 = stopWatch.Elapsed;

var lstSearch = search.ToList()

stopWatch.Stop();
var ts4 = stopWatch.Elapsed;


lstSearch = (From s In lstGetResult
      Where (s.CODE.IndexOf(txtCode.Text.Trim(), StringComparison.OrdinalIgnoreCase) >= 0 OrElse
      s.NAME.IndexOf(txtCode.Text.Trim(), StringComparison.OrdinalIgnoreCase) >= 0)
      Select New SPGet_Result With
         {.CODE = s.CODE,.NAME = s.NAME}).ToList()





使用IndexOf及其转换工作更快



非常感谢katanakensei提示:)



Converted using IndexOf and its work more faster

many thanks "katanakensei" for hint :)


这篇关于Linq查询需要时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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