Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
178 views
in Technique[技术] by (71.8m points)

c# - What's the difference between select new VS foreach (...) new

Is there any difference between

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

and

 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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are a few differences.

  1. The first is slightly clearer.

  2. 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.

  3. 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.

This query could also be written:

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...