Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array.Length vs Array.Count [duplicate]

Tags:

arrays

c#

.net

Possible Duplicate:
count vs length vs size in a collection

In .NET, pretty much all collections have the .Count property.

Sometimes I wonder if it would be better to have it on Array as well, directly though, not through ICollection.

It's just something you make an exception in your mind only for arrays.

So is it better to be "more correct" or "more uniform" in this case?

like image 316
Joan Venge Avatar asked Oct 01 '09 23:10

Joan Venge


People also ask

How to find the Count of an array in JavaScript?

The count of an array can be found using the length property, also known as the JavaScript Array Length. The length property can do multiple jobs, including returning or setting the number of elements.

How to set the length of an array in JavaScript?

The length property sets or returns the number of items in an array. The value of a length property is the integer with a positive sign and a value less than 2 to the 32nd power. To set the length of the array, use the array.length =number syntax. The length property returns a Number, representing the number of elements in the array object.

How to find the length of an array in PowerShell?

If there are more than 2,147,483,647 elements in an array, the LongLength property is handy. Moreover, Count is an alias for the Length property. You can also use Count to find the length of an array. It is easy to find the number of items stored in an array in PowerShell.

What is the difference between longlength and count in JavaScript?

If there are more than 2,147,483,647 elements in an array, the LongLength property is handy. Moreover, Count is an alias for the Length property. You can also use Count to find the length of an array.


2 Answers

In many cases where a one-dimensional array is used, it's essentially being used as a fixed-size list.

Personally I will often declare an array as IList<T>, and use the Count property rather than Length:

IList<string> strings = new string[] { ...};

Another useful member of IList<T> that does not exist in Array is the Contains() method.

like image 197
Joe Avatar answered Oct 17 '22 05:10

Joe


If you're using C# 3.0, you may use Enumerable.Count() extension method that works on all IEnumerable implementations, including lists, arrays and dictionaries.

It causes some overhead, but it's usually tolerable.

like image 35
elder_george Avatar answered Oct 17 '22 04:10

elder_george