It is a base interface that enables us to loop or iterate over an Collection.
The most important note about IEnumerable is that when you go through an object or collection it just holds the state of a single item at a time.
It has a good performance when you are iterating through big objects or collections because it does not load the entire object to memory in order to make iteration. for instance, suppose you decided to read a large file line by line and doing something on that, therefore you can write your own ReaderEnumrable to read your file with high performance.
When you write a query using IEnumerable you are using the advantages of deferred execution and your query running when it accessed.
Each time you run you iterate through a collection, a different
collection created. For example in the following code each time the listOfFiles
accessed the ListOfAllFiles
execute again.
public static void Main()
{
var listOfFiles = ListOfAllFiles();
var filesCount = listOfFiles.Count();
var filesAny = listOfFiles.Any();
var fileIterate = listOfFiles.Select(x => x.FullName);
}
private static IEnumerable ListOfAllFiles()
{
foreach(var file in Directory.EnumerateFiles(Environment.CurrentDirectory))
{
yield return new FileInfo(file);
}
}