选择新的VS foreach(...)新有什么区别 [英] What's the difference between select new VS foreach (...) new

查看:104
本文介绍了选择新的VS foreach(...)新有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 int i = 0;
 var myItems = (from source in datasource
                         select new MyObject
                         {
                             LabelId = i++,
                             Label = source.SourceName,
                             Data = source.TotalCount
                         }).ToList();

 int i = 0;
 List<MyObject> myItems = new List<MyObject>();
 foreach (var source in datasource)
        {
            MyObject myItem = new MyObject()
            {
                Label = item.SourceName,
                LabelId = i++,
                Data = item.TotalCount                
            };
            myItems.Add(myItem);
        }           

在处理性能/复杂性时间时?

When dealing with performance / complexity time ?

推荐答案

有一些区别.

  1. 第一个稍微清晰些.

  1. The first is slightly clearer.

对于某些数据源(链接到SQL是经典示例,但任何IQueryable数据源都可以这样做),select语句实际上不会以您期望的方式遍历集合.将select语句转换为IQueryProvider可以理解的查询.根据您的数据源是什么,这可以节省您和远程(SQL)之间的带宽,并可能允许更优化的查询.

For some data sources (Link to SQL is the classic example but any IQueryable datasource may do this), the select statement won't actually iterate through the collection in the way you might expect. The select statement will be translated into a query which can be understood by the IQueryProvider. Depending on what your datasource is, this could save bandwidth between you and the remote (SQL) and possibly allow a more optimised query.

如果您没有立即调用.ToList(),在您枚举结果之前什么也不会发生.在某些情况下,这可以节省曾经执行的代码.有时最好避免调用.ToList()以防止 n + 1问题.在某些情况下,最好调用.ToList(),例如,当您需要多次迭代结果时.

Had you not immediately called .ToList(), nothing would have happened until you enumerated the result. In some cases, this can save code ever being executed. There are times when it is better to avoid calling .ToList() to prevent the n+1 problem. There are also times it is better to call .ToList(), such as when you need to iterate the result multiple times.

此查询也可以写为:

var myItems = datasource.Select((i, item) => new MyObject
{
    Label = item.SourceName,
    LabelId = i,
    Data = item.TotalCount
}.ToList();

我个人比较清楚,尽管这可能是个人喜好问题.它确实具有从您的作用域中删除i变量的优点,这总是很好,通常被认为是好的做法.

Which I find clearer personally, although that may be a matter of taste. It does have the advantage of removing the i variable from your scope, which is always nice and generally considered good practice.

这篇关于选择新的VS foreach(...)新有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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