Sun
Sun

Reputation: 4718

No count method on an Array in C#

I'm using the select method on a DataTable within a DataSet to return an array of DataRows. This works fine, but on my array I don't have a Count method??

I can't understand why, I've used almost the exact statement within another application and I do have the Count method.

I've checked the reference to System.Data in both apps and they are the same. I've also checked the using statement at the top of the class and they are both set the same. i.e. using System.Data;

Here is my code:

DataRow[] selectedRecords = myDataset.Tables["Records"].Select();

now I'm trying to do :

selectedRecords.Count()

but I have no Count Method!?!?!

I'm using C# 4.0

Thanks in advance.

Upvotes: 1

Views: 765

Answers (5)

moribvndvs
moribvndvs

Reputation: 42497

Arrays use Length. However, if you import the Linq namespace, there is a Count() extension method.

Upvotes: 5

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112344

While you can use the Length property as others explained, an array also implements the IList interface, which in turn implements ICollection which defines a Count property. However, it is implemented explicitly in arrays, which means that you can access it only through the interface

public int GetCountOf(ICollection coll) {
    return coll.Count;
}

...

int cnt = GetCountOf(myArray);

Or

int cnt = ((ICollection)myArray).Count;

Count here returns the length of the array and not the count of the items contained in the array, i.e. the array could have all null entries.

Upvotes: 0

AakashM
AakashM

Reputation: 63338

  1. To be able to .Count() an array, you need a using System.Linq; to be in force
  2. Or you could just use .Length...

Upvotes: 4

Hans Z
Hans Z

Reputation: 4744

You're looking for

selectedRecords.Length;

Upvotes: 4

Panagiotis Kanavos
Panagiotis Kanavos

Reputation: 131334

Use Array.Length, not Count. Arrays do not have a Count property. If you are trying to use LINQ's Count() method specifically, you should import the System.Linq namespace

Upvotes: 5

Related Questions