Home >Backend Development >C++ >IEnumerable vs. List in C#: When Should You Choose Which?
The differences and performance effects of IenuMerable and List in the c#
When treating the collection in C#, the difference between
and is very important. IEnumerable
Represents a enumerator, which provides a method of traversing the collection; List
is the specific implementation of the IEnumerable
interface. List
IEnumerable
Consider the following two Linq query:
The working principle of the enumerator
<code class="language-csharp">List<animal> sel1 = (from animal in Animals join race in Species on animal.SpeciesKey equals race.SpeciesKey select animal).Distinct().ToList(); IEnumerable<animal> sel2 = (from animal in Animals join race in Species on animal.SpeciesKey equals race.SpeciesKey select animal).Distinct();</code>
When using , debugging will show members such as "Inner" and "OUTER", which may be confusing. "Inner" members include objects from the connection set (Species), and "OUTER" members include objects from the initial set (Animal). Query using these members to perform the connection operation.
Performance considerations IEnumerable
is usually more favored because it is delayed until the enumeration query. Using will be forced to calculate and specific results immediately, which may limit optimization opportunities. But if you need to perform a query multiple times, it will be converted to
more efficient, because it can prevent calculating query each time.
IEnumerable
Use scene ToList()
Applicable to the following situation: List
Want to delay the execution until later. Want to optimize query performance.
Multiple iterations may be required. IEnumerable
List
IEnumerable
The above is the detailed content of IEnumerable vs. List in C#: When Should You Choose Which?. For more information, please follow other related articles on the PHP Chinese website!