If I have a very large IEnumerable
collection, in the order of millions of objects, that would be too large to load all at once. The collections is returned via a yield method:
private static IEnumerable<MyData> ExtractModelsFromDb()
{
using (DbDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
Load MyData
yield return MyData;
}
reader.Close();
}
}
This Data is consumed in a single Foreach
loop:
public void RunStuff()
{
var myCollection = ExtractModelsFromDb();
foreach (var data in myCollection)
{
//DO STUFF
}
}
I know that the collection under the IEnumerable
is getting loaded one object at a time, but are the objects getting removed once they have been used in the ForEach
or do they remain in the collection until the ForEach
is complete.
IEnumerable is suitable for querying data from in-memory collections like List, Array and so on. While querying data from the database, IEnumerable executes "select query" on the server-side, loads data in-memory on the client-side and then filters the data.
IEnumerable is best to query data from in-memory collections like List, Array etc. IEnumerable doesn't support add or remove items from the list. Using IEnumerable we can find out the no of elements in the collection after iterating the collection. IEnumerable supports deferred execution.
IEnumerable is a deferred execution while List is an immediate execution. IEnumerable will not execute the query until you enumerate over the data, whereas List will execute the query as soon as it's called. Deferred execution makes IEnumerable faster because it only gets the data when needed.
IEnumerable is definitely an interface. Save this answer.
It depends on the implementation. It is not against the specification for an IEnumerable
to store the values in the sequence that it represents. In fact, a List<T>
is an IEnumerable<T>
that does exactly that!
Now, for the IEnumerable
that you have, it will not store the objects after it returns them. DbDataReader
s merely stream the results to you, and yield return
ing them will not store them. So, your foreach
is just streaming through the result set from DbDataReader
, and no one is storing them as you go gently down the stream.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With