简体   繁体   English

在这种情况下哪个更有效? LINQ查询还是FOREACH循环?

[英]Which is more efficient in this case? LINQ Query or FOREACH loop?

In my project, I implemented a service class which has a function naming GetList() which is as follows: 在我的项目中,我实现了一个服务类,该类具有一个命名为GetList()的函数,如下所示:

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();
}

which can also be implemented as 也可以实现为

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

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. 因为我的项目有很多地方必须使用下拉菜单。

Please, just use the LINQ version. 请使用LINQ版本。 You can perform optimizations later if you profile and determine this is too slow (by the way, it won't be). 如果您分析并确定速度太慢(顺便说一句,速度不会太慢),可以稍后执行优化。 Also, you can use the functional-style LINQ to make a single expression that I think reads better. 同样,您可以使用功能样式的LINQ来制作一个我认为更好的单个表达式。

IList<SUB_HEAD> GetList(string u)
{
    return context.DB.SUB_HEAD.Where(s => s.head_code == u).ToList();
}

The ToList() method is going to do exactly the same thing as you're doing manually. ToList()方法将执行与手动操作完全相同的操作。 The implementation in the .NET framework looks something like this: .NET框架中的实现如下所示:

public static class Enumerable
{
    public static List<T> ToList<T>(this IEnumerable<T> source)
    {
        var list = new List<T>();
        foreach (var item in source)
        {
            list.Add(item);
        }
        return list;
    }
}

If you can express these 4 lines of code with the characters " ToList() " then you should do so . 如果可以用字符“ ToList() ”表示这4行代码,则应该这样做 Code duplication is bad, even when it's for something this simple. 代码重复是不好的,即使是为了简单的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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