Problem
I’m trying to learn the “functional” part of C#/.Net for work, and I’m not sure if this is a good way to write this statement.
I was also trying to reduce duplicated code while not introducing too many allocs. From my understanding everything created by new here will be flagged for release once the .ForEach() is finished. Or the compiler optimizes the news out.
enum Fruits {Apple, Banana, Pear, Peach, Orange, Lychee}
new List<Fruits>
{
Fruits.Apple, Fruits.Banana, Fruits.Orange, Fruits.Lychee
}
.ForEach(x => Eat(x));
Just to note. I’m aware I could have written it the foreach loop way aswell
foreach (var x in new List<Fruits>{Fruits.Apple, Fruits.Banana, Fruits.Orange, Fruits.Lychee})
{
Eat(x);
}
Solution
I can see only a single new
there so it doesn’t really matter in this context. If you have code that creates millions of them I suggest asking a new question with the actual code. As far as this one is concerned you’ll fine with a single line where you let Enum
grab all the values and pass Eat
to the Select
without the lambda as its signature matches the lambda.
var results = Enum.GetValues<Fruits>().Select(Eat);