In .NET,
and are the two basic data structures that indicate the object sequence. Both can be used together with the expression formula of Linq (Language Integration) to perform data conversion and aggregation, but they are different in terms of behavior and performance characteristics. IEnumerable
List
Entrectional behavior
is an interface that defines the behavior of the iterative element sequence. It provides the method, which returns an object of the interface. When you iterate the collection, the enumers traversed one element at one time.
In the code of code you provide, the type of IEnumerable
variable is GetEnumerator()
. When you debug and check it, you will notice members such as "Inner" and "OUTER". These members cannot be directly accessed in the IEnumerator
instance. These members are part of the internal implementation of Linq and the underlying query pipeline. IEnumerable
sel
Performance precautions IEnumerable<animal>
List<animal>
In terms of performance,
On the other hand, use the
method to convert to to force the query immediately and load all the results to the memory. If you need to access data multiple times, this may be more efficient because it eliminates duplicate expenses.
Generally speaking, when you only need to iterate the sequence and want to use a delay evaluation, it is recommended to use IEnumerable
. If you need to access the data multiple times or you need to store it in the static data structure, it can be converted to
.ToList()
Specific examples IEnumerable
List
to perform a more efficient database query. By maintaining the initial query (allSpotted ()) as IEnumerable
, you can use List
and
However, if you need to enumerate the leopard and dumplings many times, it will be converted to a list to use more efficient. In this way, each set of database queries will be performed only once.
The above is the detailed content of IEnumerable vs. List in LINQ: When Should I Use Each?. For more information, please follow other related articles on the PHP Chinese website!