Count selectlist items (count IEnumerable)
Asked Answered
U

2

6

As you can see here and here I'm not a good friend of asp.net MVC's SelectList.
This time I'm wondering how to count the items in it. I want to show a label instead of a dropdown if the possible items don't offer any choice (items.count <2).

--EDIT--

Although Will's answer probably works too, the easy way to go is call

.GetListItems().Count()

This disables any lazy fetching you would have, but since they're gonna be in a dropdown anyway, I don't think that should be a problem.

Upthrow answered 19/11, 2008 at 13:42 Comment(2)
This appears to be outdated. In MVC version 1.0 this does not work. Intellisense says the SelectList is still an IEnumerable but the GetListItems() method is not available.Bucella
Indeed, this is outdated. Furthermore I now pass the Ienumerable itself on to the view and create the SelectList on the spot. This feels better to me because the controller shouldn't be bothering with selectlist as this is a view specific datatype.Upthrow
E
4

Linq has an extension method for IEnumerable called Count().

Emilie answered 19/11, 2008 at 13:56 Comment(0)
Z
3

Linq does not have an extension method for IEnumerable called Count(). Count() is implemented for IEnumerable, which is a big difference.

Zingaro answered 6/1, 2011 at 12:55 Comment(1)
Potato, potato - it's still an extension method. Unless you were referring to a different type of implementation, in which case I would like to be educated.Bayly

© 2022 - 2024 — McMap. All rights reserved.