Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

store "N" number of records within an array of a fixed size

Tags:

c#

Is it possible to store within an array a rolling set of values without exceeding the set index?

For example I put together a basic console example at as follows:

static void Main(string[] args)
{
    int[] myvalue;
    myvalue = new int[10];

    for (int i = 0; i < 20; i++)
    {
        Console.WriteLine("Array {0} is {1}", i, myvalue[i]);         
    }
    Console.ReadLine();

}

In the current approach I get an index out of bounds exception. What I would like to do is to limit the array to 10 items but as the count increases overwrite the existing items with new values. Therefore I could iterate through 100 times but the array would only show the last ten values (89-99) at the end of the routine.

If an array is not the best approach I would welcome any suggestions as to how to store this in memory.

thank you

like image 322
rlcrews Avatar asked Dec 05 '22 18:12

rlcrews


1 Answers

You could use a List to store the values, then wrap the Add method to handle the limit on the number of items. This would take care of all the "slide down" logic for you.

const int MAX_ITEMS = 10;
List<int> list = new List<int>();

void AddItem(int k)
{
    list.Add(k);
    if (list.Count > MAX_ITEMS)
    {
        // discard the item at the front of the list
        list.RemoveAt(0);
    }
}

Whenever you want to add a value, you just call AddItem(n), for example:

for (int i = 0; i < 100; i++)
{
    AddItem(i);
}

Whenever you want to read out the values, you can simply do:

for (int i = 0; i < list.Count; i++)
{
    Console.WriteLine(list[i]);
}

This also has the advantage that you can put less than the maximum number of items in (say you only have 6 instead of 10) and it will still work correctly (you don't have to worry about unfilled array items).

like image 108
Brian Rogers Avatar answered Feb 19 '23 10:02

Brian Rogers