1

In C# if I have the following object:

IEnumerable<Product> products;

and if I want to get how many elements it contains I use:

int productCount = products.Count();

but it looks like there is no such method in VB.NET. Anybody knows how to achieve the same result in VB.NET?

BenMorel
  • 34,448
  • 50
  • 182
  • 322
CiccioMiami
  • 8,028
  • 32
  • 90
  • 151

3 Answers3

3

Count is available in VB.NET:

   Dim x As New List(Of String)
   Dim count As Integer

   x.Add("Item 1")
   x.Add("Item 2")

   count = x.Count

http://msdn.microsoft.com/en-us/library/bb535181.aspx#Y0

Magnus
  • 45,362
  • 8
  • 80
  • 118
Darren
  • 68,902
  • 24
  • 138
  • 144
0

In later versions of .net, there is an extension method called Count() associated with IEnumerable<T>, which will use IList<T>.Count() or ICollection.Count() if the underlying enumerator supports either of those, or will iteratively count the items if it does not.

An important caveat not always considered with this: while an IEnumerable<DerivedType> may generally be substituted for an IEnumerable<BaseType>, a type which implements IList<DerivedType> but does not implement ICollection may be efficiently counted when used as an IEnumerable<DerivedType>, but not when cast as IEnumerable<BaseType> (even though the class would support an IList<DerivedType>.Count() method which would return the correct result, the system wouldn't look for that--it would look for IList<BaseType> instead, which would not be implemented.

supercat
  • 77,689
  • 9
  • 166
  • 211
0

In general, IEnumerable won't have a Count unless the underlying collection supports (eg List).

Think about what needs to happen for a generic IEnumerable to implement a Count method. Since the IEnumerable only executes when data is requested, in order to perform a Count, it needs to iterate through till the end keeping track of how many elements it has found.

Generally, this iteration will come to an end but you can setup a query that loops forever. Count is either very costly time-wise or dangerous with IEnumerable.

iheanyi
  • 3,107
  • 2
  • 23
  • 22
  • IEnumerable always has `.Count()` as an extension method. If the underlying collection is `ICollection` and has a `Count` property, `Count()` calls it. If it doesn't, `Count()` would indeed iterate the entire collection. – Tsahi Asher Jun 22 '15 at 11:00
  • @TsahiAsher so how does what you say make my answer incorrect? As far as I can see, the IEnumerable interface does not provide a Count method. Of course, extension methods get around this. One can write extension methods for anything you want. – iheanyi Jun 23 '15 at 19:35
  • By that logic, IEnumerable never has a Count, regardless of the underlying collection. If you ignore extension methods, you would have to cast it to ICollection anyway (if possible). But if you do consider extension methods, there is always a Count() extension method which is part of the .NET Framework. – Tsahi Asher Jun 24 '15 at 14:06