Difference Between List and IEnumerable in C#? One Is 'Lazy'

preview_player
Показать описание

Рекомендации по теме
Комментарии
Автор

Little missleading explanation. IEnumerable is just an interface that gives you iterator. You decribing EF implemantation.
For example to get 10th element from IEnumerable you cannot just get it by adress - arr[9]. You need to itereate by every element - one by one, as a seqeance . This gives flexibility for diffrent implementations because that way data structure that is impelementing IEnumerable can optimize memory consumption and fetch only one element at the time.
If you are have 1000 element list but you want to read only first, all elements of the List will be loaded to the memory (such a waste) . If you use IEnumerable it should load only one - when accessed.
Entity Framework implements IEnumebrable(iQuerable). If you call "toList" It will load all selected record from database to the memory (because you need to have all data to create a list). if you don't call "to List" and just itereate EF will load one element at the time (creating many select querries to the database).

psdmaniac
Автор

IEnumberable for when you only need to loop over the collection. IList for when you need the method that the interface offers, Add, Remove, InsertAt, etc, etc.

hjbbmyf
Автор

Not always true because list also implements IEnumerable and you don't need to materialize a list to get values since the values are already present. The deferred execution scenario you're talking about comes into picture when an IEnumerable is returned from an iterator block.

catchroniclesbyanik
Автор

Isn't that just for ORMs though, like EntityFramework?

If you simply have a method that takes an IEnumerable it could be a List, but it will only behave like a read-only enumerable.

SwedePlaysGames