IEnumerable vs List - What to Use? How do they work?

后端 未结 10 2509
臣服心动
臣服心动 2020-11-22 03:57

I have some doubts over how Enumerators work, and LINQ. Consider these two simple selects:

List sel = (from animal in Animals 
                         


        
10条回答
  •  天命终不由人
    2020-11-22 04:16

    The most important thing to realize is that, using Linq, the query does not get evaluated immediately. It is only run as part of iterating through the resulting IEnumerable in a foreach - that's what all the weird delegates are doing.

    So, the first example evaluates the query immediately by calling ToList and putting the query results in a list.
    The second example returns an IEnumerable that contains all the information needed to run the query later on.

    In terms of performance, the answer is it depends. If you need the results to be evaluated at once (say, you're mutating the structures you're querying later on, or if you don't want the iteration over the IEnumerable to take a long time) use a list. Else use an IEnumerable. The default should be to use the on-demand evaluation in the second example, as that generally uses less memory, unless there is a specific reason to store the results in a list.

提交回复
热议问题