ChatGPT解决这个技术问题 Extra ChatGPT

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

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

List<Animal> sel = (from animal in Animals 
                    join race in Species
                    on animal.SpeciesKey equals race.SpeciesKey
                    select animal).Distinct().ToList();

or

IEnumerable<Animal> sel = (from animal in Animals 
                           join race in Species
                           on animal.SpeciesKey equals race.SpeciesKey
                           select animal).Distinct();

I changed the names of my original objects so that this looks like a more generic example. The query itself is not that important. What I want to ask is this:

foreach (Animal animal in sel) { /*do stuff*/ }

I noticed that if I use IEnumerable, when I debug and inspect "sel", which in that case is the IEnumerable, it has some interesting members: "inner", "outer", "innerKeySelector" and "outerKeySelector", these last 2 appear to be delegates. The "inner" member does not have "Animal" instances in it, but rather "Species" instances, which was very strange for me. The "outer" member does contain "Animal" instances. I presume that the two delegates determine which goes in and what goes out of it? I noticed that if I use "Distinct", the "inner" contains 6 items (this is incorrect as only 2 are Distinct), but the "outer" does contain the correct values. Again, probably the delegated methods determine this but this is a bit more than I know about IEnumerable. Most importantly, which of the two options is the best performance-wise?

The evil List conversion via .ToList()?

Or maybe using the enumerator directly?

If you can, please also explain a bit or throw some links that explain this use of IEnumerable.


A
Amirhossein Mehrvarzi

IEnumerable describes behavior, while List is an implementation of that behavior. When you use IEnumerable, you give the compiler a chance to defer work until later, possibly optimizing along the way. If you use ToList() you force the compiler to reify the results right away.

Whenever I'm "stacking" LINQ expressions, I use IEnumerable, because by only specifying the behavior I give LINQ a chance to defer evaluation and possibly optimize the program. Remember how LINQ doesn't generate the SQL to query the database until you enumerate it? Consider this:

public IEnumerable<Animals> AllSpotted()
{
    return from a in Zoo.Animals
           where a.coat.HasSpots == true
           select a;
}

public IEnumerable<Animals> Feline(IEnumerable<Animals> sample)
{
    return from a in sample
           where a.race.Family == "Felidae"
           select a;
}

public IEnumerable<Animals> Canine(IEnumerable<Animals> sample)
{
    return from a in sample
           where a.race.Family == "Canidae"
           select a;
}

Now you have a method that selects an initial sample ("AllSpotted"), plus some filters. So now you can do this:

var Leopards = Feline(AllSpotted());
var Hyenas = Canine(AllSpotted());

So is it faster to use List over IEnumerable? Only if you want to prevent a query from being executed more than once. But is it better overall? Well in the above, Leopards and Hyenas get converted into single SQL queries each, and the database only returns the rows that are relevant. But if we had returned a List from AllSpotted(), then it may run slower because the database could return far more data than is actually needed, and we waste cycles doing the filtering in the client.

In a program, it may be better to defer converting your query to a list until the very end, so if I'm going to enumerate through Leopards and Hyenas more than once, I'd do this:

List<Animals> Leopards = Feline(AllSpotted()).ToList();
List<Animals> Hyenas = Canine(AllSpotted()).ToList();

I think they refer to the two sides of a join. If you do "SELECT * FROM Animals JOIN Species..." then the inner part of the join is Animals, and the outer part is Species.
When I've read the answers about: IEnumerable<T> vs IQueryable<T> I saw the analogical explanation, so that IEnumerable automatically forces the runtime to use LINQ to Objects to query the collection. So I'm confused between these 3 types. stackoverflow.com/questions/2876616/…
@Bronek The answer you linked is true. IEnumerable<T> will be LINQ-To-Objects after the first part meaning all spotted would have to be returned to run Feline. On the other hand an IQuertable<T> will allow the query to be refined, pulling down only Spotted Felines.
This answer is very misleading! @Nate's comment explains why. If you're using IEnumerable, the filter is going to happen on the client side no matter what.
Yes AllSpotted() would be run twice. The bigger problem with this answer is the following statement: "Well in the above, Leopards and Hyenas get converted into single SQL queries each, and the database only returns the rows that are relevant." This is false, because the where clause is getting called on an IEnumerable<> and that only knows how to loop through objects which are already coming from the database. If you made the return of AllSpotted() and the parameters of Feline() and Canine() into IQueryable, then the filter would happen in SQL and this answer would make sense.
r
rubStackOverflow

There is a very good article written by: Claudio Bernasconi's TechBlog here: When to use IEnumerable, ICollection, IList and List

Here some basics points about scenarios and functions:

https://i.stack.imgur.com/4dKYm.png


It should be pointed that this article is only for the public facing parts of your code, not the internal workings. List is an implementation of IList and as such has extra functionality on top of those in IList (e.g. Sort, Find, InsertRange). If you force yourself to use IList over List, you loose these methods that you may require
Don't forget IReadOnlyCollection<T>
It might be helpful to include a plain array [] here as well.
While it may be frowned upon, thank you for sharing this graphic and article
K
Keith

A class that implement IEnumerable allows you to use the foreach syntax.

Basically it has a method to get the next item in the collection. It doesn't need the whole collection to be in memory and doesn't know how many items are in it, foreach just keeps getting the next item until it runs out.

This can be very useful in certain circumstances, for instance in a massive database table you don't want to copy the entire thing into memory before you start processing the rows.

Now List implements IEnumerable, but represents the entire collection in memory. If you have an IEnumerable and you call .ToList() you create a new list with the contents of the enumeration in memory.

Your linq expression returns an enumeration, and by default the expression executes when you iterate through using the foreach. An IEnumerable linq statement executes when you iterate the foreach, but you can force it to iterate sooner using .ToList().

Here's what I mean:

var things = 
    from item in BigDatabaseCall()
    where ....
    select item;

// this will iterate through the entire linq statement:
int count = things.Count();

// this will stop after iterating the first one, but will execute the linq again
bool hasAnyRecs = things.Any();

// this will execute the linq statement *again*
foreach( var thing in things ) ...

// this will copy the results to a list in memory
var list = things.ToList()

// this won't iterate through again, the list knows how many items are in it
int count2 = list.Count();

// this won't execute the linq statement - we have it copied to the list
foreach( var thing in list ) ...

But what happens if you execute a foreach on an IEnumerable without converting it to a List first? Does it bring the whole collection in memory? Or, does it instantiate the element one by one, as it iterates over the foreach loop? thanks
@Pap the latter: it executes again, nothing is automatically cached in memory.
seems like the key diff is 1) whole thing in memory or not. 2) IEnumerable let me use foreach while List will go by say index. Now, if I'd like to know the count/length of thing beforehand, IEnumerable won't help, right?
@MFouadKajj I don't know what stack you're using, but it's almost certainly not making a request with each row. The server runs the query and calculates the starting point of the result set, but doesn't get the whole thing. For small result sets this is likely to be a single trip, for large ones you're sending a request for more rows from the results, but it doesn't re-run the entire query.
@shaijut It shouldn't, but it might depend on the specific provider. In Microsoft SQL Server you get a client cursor that keeps the connection open and the client just requests the next record in the set. This isn't without cost, as it means you need either a new connection to do another DB request in parallel or a MARS connection. Too much for a comment really
C
Community

Nobody mentioned one crucial difference, ironically answered on a question closed as a duplicated of this.

IEnumerable is read-only and List is not.

See Practical difference between List and IEnumerable


As a follow up, is that because of the Interface aspect or because of the List aspect? i.e. is IList also readonly?
IList is not read-only - docs.microsoft.com/en-us/dotnet/api/… IEnumerable is read-only because it lacks any methods to add or remove anything once it is constructed, it is one of the base interfaces which IList extends (see link)
That's just a matter of usage, hiding a bigger underlying problem - IEnumerable is read only because it (potentially) keeps changing. Consider the houses I have to display, in ascending order of value price (say I have 10 of them). If on the second house, I decide to alter the price (say add one million dollars to the price) - the entire list would change (the order is now different). "one at a time" and "all of them right now" are two different things.
h
h4ck3rm1k3

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<T> 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<T> 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<T> to take a long time) use a list. Else use an IEnumerable<T>. 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.


Hi and thanks for answering ::- ). This cleared up almost all my doubts. Any idea why the Enumerable is "split" into "inner" and "outer"? This happens when I inspect the element in debug/break mode via mouse. Is this perhaps Visual Studio's contribution? Enumerating on the spot and indicating input and output of the Enum?
That's the Join doing it's work - inner and outer are the two sides of the join. Generally, don't worry about what's actually in the IEnumerables, as it will be completely different from your actual code. Only worry about the actual output when you iterate over it :)
M
Matt Sherman

The advantage of IEnumerable is deferred execution (usually with databases). The query will not get executed until you actually loop through the data. It's a query waiting until it's needed (aka lazy loading).

If you call ToList, the query will be executed, or "materialized" as I like to say.

There are pros and cons to both. If you call ToList, you may remove some mystery as to when the query gets executed. If you stick to IEnumerable, you get the advantage that the program doesn't do any work until it's actually required.


m
maxisam

I will share one misused concept that I fell into one day:

var names = new List<string> {"mercedes", "mazda", "bmw", "fiat", "ferrari"};

var startingWith_M = names.Where(x => x.StartsWith("m"));

var startingWith_F = names.Where(x => x.StartsWith("f"));


// updating existing list
names[0] = "ford";

// Guess what should be printed before continuing
print( startingWith_M.ToList() );
print( startingWith_F.ToList() );

Expected result

// I was expecting    
print( startingWith_M.ToList() ); // mercedes, mazda
print( startingWith_F.ToList() ); // fiat, ferrari

Actual result

// what printed actualy   
print( startingWith_M.ToList() ); // mazda
print( startingWith_F.ToList() ); // ford, fiat, ferrari

Explanation

As per other answers, the evaluation of the result was deferred until calling ToList or similar invocation methods for example ToArray.

So I can rewrite the code in this case as:

var names = new List<string> {"mercedes", "mazda", "bmw", "fiat", "ferrari"};

// updating existing list
names[0] = "ford";

// before calling ToList directly
var startingWith_M = names.Where(x => x.StartsWith("m"));

var startingWith_F = names.Where(x => x.StartsWith("f"));

print( startingWith_M.ToList() );
print( startingWith_F.ToList() );

Play arround

https://repl.it/E8Ki/0


That's because of linq methods (extension) which in this case come from IEnumerable where only create a query but not execute it (behind the scenes the expression trees are used). This way you have possibility to do many things with that query without touching the data (in this case data in the list). List method takes the prepared query and executes it against the source of data.
Actually, I read all the answers, and yours was the one I up-voted, because it clearly states the difference between the two without specifically talking about LINQ/SQL. It is essential to know all this BEFORE you get to LINQ/SQL. Admire.
That is an important difference to explain but your "expected result" isn't really expected. You're saying it like it's some sort of gotcha rather than design.
@Neme, yes It was my expectation before I understand how IEnumerable works, but now Isn't more since I know how ;)
While this is an important concept to understand this doesn't actually answer the question.
D
Daren Thomas

If all you want to do is enumerate them, use the IEnumerable.

Beware, though, that changing the original collection being enumerated is a dangerous operation - in this case, you will want to ToList first. This will create a new list element for each element in memory, enumerating the IEnumerable and is thus less performant if you only enumerate once - but safer and sometimes the List methods are handy (for instance in random access).


I'm not sure it's safe to say that generating a list means lower performance.
@ Steven: indeed as thecoop and Chris said, sometimes it may be necessary to use a List. In my case, I have concluded it isn't. @ Daren: what do you mean by "this will create a new list for each element in memory"? Maybe you meant a "list entry"? ::- ).
@Axonn yes, I ment list entry. fixed.
@Steven If you plan to iterate over the elements in the IEnumerable, then creating a list first (and iterating over that) means you iterate over the elements twice. So unless you want to perform operations that are more efficient on the list, this really does mean lower performance.
@jerhewet: it is never a good idea to modify a sequence being iterated over. Bad things will happen. Abstractions will leak. Demons will break into our dimension and wreak havoc. So yes, .ToList() helps here ;)
A
Ananth

In addition to all the answers posted above, here is my two cents. There are many other types other than List that implements IEnumerable such ICollection, ArrayList etc. So if we have IEnumerable as parameter of any method, we can pass any collection types to the function. Ie we can have method to operate on abstraction not any specific implementation.


L
LongChalk

There are many cases (such as an infinite list or a very large list) where IEnumerable cannot be transformed to a List. The most obvious examples are all the prime numbers, all the users of facebook with their details, or all the items on ebay.

The difference is that "List" objects are stored "right here and right now", whereas "IEnumerable" objects work "just one at a time". So if I am going through all the items on ebay, one at a time would be something even a small computer can handle, but ".ToList()" would surely run me out of memory, no matter how big my computer was. No computer can by itself contain and handle such a huge amount of data.

[Edit] - Needless to say - it's not "either this or that". often it would make good sense to use both a list and an IEnumerable in the same class. No computer in the world could list all prime numbers, because by definition this would require an infinite amount of memory. But you could easily think of a class PrimeContainer which contains an IEnumerable<long> primes, which for obvious reasons also contains a SortedList<long> _primes. all the primes calculated so far. the next prime to be checked would only be run against the existing primes (up to the square root). That way you gain both - primes one at a time (IEnumerable) and a good list of "primes so far", which is a pretty good approximation of the entire (infinite) list.


L
LongChalk

The downside of IEnumerable (a deferred execution) is that until you invoke the .ToList() the list can potentially change. For a really simple example of this - this would work

var persons;
using (MyEntities db = new MyEntities()) {
    persons = db.Persons.ToList(); // It's mine now. In the memory
}
// do what you want with the list of persons;

and this would not work

IEnumerable<Person> persons;
 using (MyEntities db = new MyEntities()) {
     persons = db.Persons; // nothing is brought until you use it;
 }

persons = persons.ToList();  // trying to use it...
// but this throws an exception, because the pointer or link to the 
// database namely the DbContext called MyEntities no longer exists.