哪种情况有效? LINQ查询还是FOREACH循环? [英] which is efficient in this case? LINQ query or FOREACH loop?

查看:265
本文介绍了哪种情况有效? LINQ查询还是FOREACH循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的项目中,我实现了一个服务类,其中有一个命名为GetList()的函数,如下所示:



 IList < span class =code-keyword><   SUB_HEAD  >  GetList(string u )
{
var collection =(from context in context.DB.SUB_HEAD where(s.head_code.Equals(u))
select s);
返回collection.ToList();
}

drpdwn.datasource = Getlist();
drpdwn.databind();







也可以实现为

< pre lang =c#> Arraylist unitlist = new Arraylist();
ObjectSet< SUB_HEAD> List = subheadService.GetAll();
foreach (SUB_HEAD单位列表中)
{
unitlist。加入(unit.sub_head_code);
}

drpdwn.datasource = unitlist;
drpdwn.databind();



这样做的目的是填充下拉菜单。



我的问题是上述哪种方法在处理方面会更有效?因为我的项目有很多地方我必须使用下拉菜单。

解决方案

作为一般的经验法则,我更喜欢在LINQ上循环foreach循环;从性能的角度来看。



参见这个 [ ^ ]和 this [ ^ ]



[请鼓励参与投票的解决方案或有效的答案你是


从代码的外观来看,你正在从数据库中检索菜单内容并担心性能。

如果是这种情况,那么最好的解决方案是不要调用数据库。

在启动时加载来自数据库的各种下拉菜单结果在字典中。

字典可以是一个懒惰加载的静态应用程序范围对象。

或者,按键(u)将菜单存储在缓存中并重新加载如果不在缓存中则缓存。这样做的好处是允许您设置缓存超时,强制定期刷新菜单,允许更改菜单(数据库),而无需重新启动应用程序。


in my project i implemented a service class which has a function naming GetList() which is as follows:

IList<SUB_HEAD> GetList(string u)
{
    var collection = (from s in context.DB.SUB_HEAD where (s.head_code.Equals(u))
    select s);
    return collection.ToList();
}

drpdwn.datasource=Getlist();
drpdwn.databind();




which can also b implemented as

Arraylist unitlist= new Arraylist();
ObjectSet<SUB_HEAD> List = subheadService.GetAll();
foreach(SUB_HEAD unit in List)
{
    unitlist.Add(unit.sub_head_code);
}

drpdwn.datasource=unitlist;
  drpdwn.databind();


Purpose of doing this is to populate dropdown menu.

My question is that "which of the above method will be more efficient with respect to processing?" because my project have lot of places where i have to use drop down menu.

解决方案

As a general rule of thumb I prefer for loop over foreach loop over LINQ; that is from Performance point of view.

See this[^] and this[^]

[Please encourage participation by up-voting solutions or answers that work for you]


From the looks of your code, you are retrieving the menu content from the database and are concerned about performance.
If that is the case, then the best solution is to not make the call to the database.
Load the various dropdown menus from the database at startup and store the results in a dictionary.
The dictionary could be a Lazy loaded static application wide object.
Alternately, store the menus by key (u) in the cache and reload and cache if not in cache. This has the advantage of allowing you to set a cache timeout, forcing the menus to be refreshed on a regular basis, allowing for menu (database) changes without having to restart the app.


这篇关于哪种情况有效? LINQ查询还是FOREACH循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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