2

I have this array:

var categoryGroups = new[] {
    new CategoryGroupSource { Id = 1,  Name = "Conversation" },
    new CategoryGroupSource { Id = 2,  Name = "Business" },
    new CategoryGroupSource { Id = 3,  Name = "Education" }
};

I tried to do a count on this:

categoryGroups.Count

But it is giving me an error saying this will only work with a list. Can someone give me advice on this?

Note I am also doing this:

foreach (CategoryGroupSource categoryGroup in categoryGroups)
{
    db.Insert(categoryGroup);
}

Does the foreach work for arrays and lists?

Damith
  • 59,353
  • 12
  • 95
  • 149
Alan2
  • 19,668
  • 67
  • 204
  • 365

6 Answers6

8

use categoryGroups.Length for the arrays

var categoryGroups = new[] {
            new CategoryGroupSource { Id = 1,  Name = "Conversation" },
            new CategoryGroupSource { Id = 2,  Name = "Business" },
            new CategoryGroupSource { Id = 3,  Name = "Education" }
        };

int count = categoryGroups.Length;

Does the foreach work for arrays and lists?

Yes.

Using foreach with Arrays (C# Programming Guide)

Damith
  • 59,353
  • 12
  • 95
  • 149
1

You might have used

categoryGroups.Length

Every array has a Length. In the C# language we access the Length property on a non-null array. Length has no parentheses, as it is a property. It is read-only—you cannot assign Length.

And yes of-course foreach works for arrays and list. and if you wanted to see Why List is better than Arrays you can read more here

Community
  • 1
  • 1
Mohit Shrivastava
  • 12,996
  • 5
  • 31
  • 61
1

foreach works of arrays and lists

For Counting no of element in array

change

categoryGroups.Count

to

categoryGroups.Length
Hassan Tariq
  • 730
  • 7
  • 15
0

In .NET, arrays and strings (which are technically special character arrays) have a Length property, and just about every other collection has a Count property for this counting elements.

In addition to this, the System.Linq namespace provides a Count() extension method for the IEnumerable<T> interface, which most collections implement. So for an array you can also use myArray.Count(), if you're using System.Linq;.

Note that Count() is a method on arrays and any collection implementing IEnumerable<T>, while Count is a property of some collections.

JamesFaix
  • 5,975
  • 3
  • 30
  • 62
0

foreach works with all types that implements IEnumerable.

You were not able to access .count property because it is available for List types, but you are using Array.

Sateesh Pagolu
  • 8,203
  • 2
  • 22
  • 42
0

I agree if you just want it to say the amount of values in the array you could just print the length value of the array.