C#
C#

help

Root Question Message

Gladiator
Gladiator12/6/2022
Best way to Convert a single element to IEnumerable element

What is the best way (performance, memory, GC) to Convert a single element to IEnumerable<Element> elements?
T => IEnumerable<T>
return new []{element};
yield return element;
AntonC
AntonC12/6/2022
I would guess the best best way would be to make a custom class which holds a single (or N) elements, but I've seen people just do new[]{it} all the time
AntonC
AntonC12/6/2022
so you'd need a class that implements IEnumerable, and an implementation of IEnumerator that would work on that class
AntonC
AntonC12/6/2022
it's not that much code, just a bit of boilerplate
AntonC
AntonC12/6/2022
idk what yield return it gives you honestly, you should look at the lowered code, it might just be doing the class thing I described
mtreit
mtreit12/7/2022
@509697647246966804 , @296666311688454144 I was curious about this so I benchmarked it. Wrapper class certainly seems like the way to go.
AntonC
AntonC12/7/2022
i was suggesting 2 classes, an enumerable and an enumerator
AntonC
AntonC12/7/2022
I would guess if you do two classes you get the same results as with the yield version
ContactFrequently Asked QuestionsJoin The DiscordBugs & Feature RequestsTerms & Privacy