how to count elements inside an array?

if I have an array of 32 byte for example.
but there's only 8 slots used.
How can i count the number of slots used.
.length() or .getlength(0) only give me the total size of the array.

Thank ya'll

Donkaiser


Answer this question

how to count elements inside an array?

  • Cine

    Consider using System.Collections.ArrayList in place of a classic, fixed size array.

    The ArrayList.Capacity gets/sets the number of "slots" in the ArrayList, the ArrayList.Count property gives the number of slots actually used.

    See 'ya


  • Aalok Bhatwal

    You could also use a Nullable Byte array.

    static void Main()
    {
    Nullable<Byte>[] nullableByteArray = new Nullable<Byte>[32];
    nullableByteArray[0] = 1;
    nullableByteArray[5] = 2;
    nullableByteArray[7] = 3;
    nullableByteArray[9] = 4;
    MessageBox.Show(GetNumberOfSlotsUsed(nullableByteArray).ToString());

    }

    static int GetNumberOfSlotsUsed(Nullable<Byte>[] arr)
    {
    int count = 0;
    for (int j = 0; j < arr.Length; j++)
    {
    if (arr[j] != null)
    count++;

    }
    return count;
    }

  • Darshak

    By your question I assume there is some value you are using as "not used", something like 0x00, for instance. If this is the case, you can either iterate through the whole, counting the occurrences, or resort to a predicate. The first is probably the most efficient, and would be something like:

    int CountUsed (byte [] myarray, byte nullValue) {
    int count = 0;
    foreach (byte b in myarray) {
    if (b != nullValue)
    count++;
    }
    return count;
    }

    An alternative could be to create a predicate and use the FindAll<T> method. For instance:"

    private static bool NotNull (byte b) {
    return b != 0x00;
    }

    ...
    int count = Array.FindAll (myarray, NotNull).Length;

    This is nicer, but will create a temporary array containing the result of FindAll. Not really an issue with 32 bytes, but might get ugly in the long run. Also, it still uses an enumeration, so it's better you don't call it thousands of times.

    In conclusion, the above solutions will work if you are really stuck with an array. If you are not, do yourself a favour and step to a List<byte>.

    HTH
    --mc


  • EngineerPete

    As far as I know there really is no way to tell, especially with value types such as integers/bytes since these are not "null". If they were reference objects you could use a for loop and check if a slot is null. Ultimately This would beed be something that you would have to keep track of yourself or you would have to use some generic or other form of Collection that lets you specify the grow by size but lets you control the actual length by the number of items you add. e.g. List
    <Byte> myBytes = new List<Byte>;
    myBytes.Add(0x30);
    Then you could get the length/count.

    Hope this helps.


  • how to count elements inside an array?