Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count of System.Collections.Generic.List

ViewBag.EquipmentList = myInventoryEntities.p_Configurable_Equipment_Request_Select(Address_ID, false).Select(c => new { Value = c.Quantity + " " + c.Device_Name + " (s)", ID = c.Device_ID.ToString() }).ToList();

In Razor i want to do the following

@ViewBag.EquipmentList.Count

But Count is always == 1

I know i can iterate in a foreach but would rather a more direct approach.

Perhaps I am conceptually off?

like image 807
Pinch Avatar asked Oct 22 '12 16:10

Pinch


2 Answers

EDIT: Okay, so now it seems like you've got past Count not executing:

But Count is always == 1

Sounds like you're always fetching a list with exactly one entry in. If that's unexpected, you should look at why you're only getting a single entry - start with debugging into the code... this doesn't sound like a Razor problem at all.


If your value were really a List<T> for some T, I believe it should be fine. The expression ViewBag.EquipmentList.Count would evaluate dynamically at every point.

In other words, if you're really, really using the assignment code shown, it should be okay.

If, however, the value is just some implementation of IEnumerable<T> which doesn't expose a Count property, then you'd need to use the Enumerable.Count() extension method - and you can't use normal "extension method syntax" with dynamic typing. One simple fix would be to use:

Enumerable.Count(ViewBag.EquipmentList)

... which will still use dynamic typing for the argument to Enumerable.Count, but it won't have to find the Count() method as an extension method.

Alternatively, make sure that your value really is a List<T>. If it's actually an array, you should be able to change the code to use the Length property instead.

like image 120
Jon Skeet Avatar answered Sep 30 '22 10:09

Jon Skeet


@ViewBag.EquipmentListNI.Count()
like image 26
ChrisBint Avatar answered Sep 30 '22 08:09

ChrisBint