1

I wanted to fill WinForms Combobox with enum values, yet when I tried to do it with Linq, no items were added to the Combobox. However, the foreach variant works just fine.

My Linq:

Enum.GetNames(typeof(AgeCategory))
    .Select(x => cbCategory.Items.Add(x));

My foreach:

foreach (var category in Enum.GetNames(typeof(AgeCategory)))
{
    cbCategory.Items.Add(category);
}

Also, if you know about a better way to do this, I'm open to different solutions.

Tim
  • 5,435
  • 7
  • 42
  • 62
  • 4
    The Linq version is faulty: the Select method does a projection to create a collection of items, but here you are just calling a method that returns an index ... so, why not? Otherwise you don't [execute the query](https://learn.microsoft.com/dotnet/standard/linq/deferred-execution-lazy-evaluation), therefore nothing is done, unless for example you call ToList. Personally, I found such code esoteric, not clean, and to avoid, in addition to be not efficient, and therefore *dangerous*. –  May 27 '21 at 15:17

1 Answers1

6

Enumerable.Select is using deferred execution. That means it's executed if you use a foreach or other method like ToList/ToArray. Until then it just builds the query.

So why that compiles at all, what you are doing there? You have to look at ComboBox.ObjectCollection.Add to see that it's not void(returns nothing) but returns the index of the item that you have added. So you are selecting integers here, which is not what you want.

You could use this approach:

cbCategory.Items.AddRange(Enum.GetNames(typeof(AgeCategory)));

As a rule of thumb: use LINQ to query something not to modify(add) something.

Worth reading: What are the benefits of a Deferred Execution in LINQ?

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939