1

I need to use a data structure that would keep the latest X elements of a list. A colleague gave me this solution:

        int start = 0;
        const int latestElementsToKeep = 20;
        int[] numbers = new int[latestElementsToKeep];
        for (int i = 0; i < 30; i++)
        {
            numbers[start] = i;
            if (start < numbers.Length - 1)
            {
                start++;
            }
            else
            {
                start = 0;
            }
        }

So after this is run, the numbers array has numbers 19-29 (the latest 20 numbers).

That's nice, but difficult to use this in the real world. Is there an easier way to do this?

4

3 回答 3

6

This seems like a pretty standard Circular Buffer. My only suggestion would be to create a class for it or download one of the libraries available. There seem to be a few promising looking ones near the top of the Google results.

于 2012-11-28T22:34:02.053 回答
1

Easier way to do this:

int[] numbers = new int[latestElementsToKeep];
for (int i = 0; i < 30; i++)
    numbers[i % latestElementsToKeep] = i;

Modulus operator returns the reminder of dividing i by latestElementsToKeep. When i reaches latestElementsToKeep, you will start from the beginning.

于 2012-11-28T22:40:55.293 回答
0

For a range of numbers, you can use:

int keep = 20;
int lastItem = 29;
int[] numbers = Enumerable.Range(lastItem - keep, keep).ToArray();

To get the last items from any collection (where you can get the size), you can use:

int keep = 20;
someType[] items = someCollection.Skip(someCollection.Count() - keep).ToArray();
于 2012-11-28T22:52:10.937 回答