C
C#2w ago
AceOfAces

IEnumerable and loops

A bit of a rapid-fire question: if I only need to iterate on a collection once, is it OK to use IEnumerable? For example, using Directory.EnumerateFiles(path) to filter out the files in separate lists.
12 Replies
Unknown User
Unknown User2w ago
Message Not Public
Sign In & Join Server To View
AceOfAces
AceOfAcesOP2w ago
OK. But why would I use IEnumerable in a case like this, compared to saving the results to a List?
mtreit
mtreit2w ago
What do you mean? If you only need to enumerate something, using IEnumerable gives more flexibility because the underlying type could be a List or an Array or a HashSet, etc.
Unknown User
Unknown User2w ago
Message Not Public
Sign In & Join Server To View
mtreit
mtreit2w ago
The code doesn't care what the underlying type is.
Unknown User
Unknown User2w ago
Message Not Public
Sign In & Join Server To View
AceOfAces
AceOfAcesOP2w ago
It iterates on every entry in a collection.
Unknown User
Unknown User2w ago
Message Not Public
Sign In & Join Server To View
AceOfAces
AceOfAcesOP2w ago
I never used IEnumerator directly, oustide of LINQ and stuff like Directory.EnumerateFiles. So I was wondering if they could be used (and if yes, are they any performance penalties).
Unknown User
Unknown User2w ago
Message Not Public
Sign In & Join Server To View
mtreit
mtreit2w ago
Using IEnumerable is fine. In fact it can be preferred. There is generally no performance issue. IF the IEnumerable is backed by an expensive query then you may want to materialize it into a List or an Array if there is a chance you need to enumerate it more than once. Enumerating multiple times will cause the underlying query to be evaluated multiple times which can be a performance pitfall. But if it's just backed by an in-memory data structure it's generally fine. (Although usually if you can avoid enumerating something multiple times that is also preferred.)
AceOfAces
AceOfAcesOP2w ago
Noted. Thank you very much.

Did you find this page helpful?