开发者

How can i add dictionary backward?

im using dictionary to store realtime coming date like stock rates. and i want to store maximum 10000 ticks, and the last time coming is index.of 0 . but with dictionary add method, the last tick added isn't index.of 0 , it keeps increasing until 10000 .

Are there any way i can get around it.

    public static Dictionary<string, int> storePrice(string intru, double price)开发者_运维技巧
    {
        Dictionary<string, int> d = new Dictionary<string, int>();
        d.Add(intru, price);
    }

Thanks


Dictionaries have no order, so you can't even add them "forwards"


What you need here may be a Stack<T> not a dictionary. A Stack is First In Last Out, so at the top of your Stack would be the latest item you put in there. See here:

http://msdn.microsoft.com/en-us/library/system.collections.stack.aspx


It sounds like you want a circular buffer. Basically you model this with a fixed size of array, one index to indicate the start, and one index to indicate the end. Removing an item from the start is just a case of bumping up the start index and wiping out the value in array; adding an item to the end is just a case of bumping up the end index and the start index if the buffer is "full". Any time you increment an index beyond the size of the array, you set it back to 0 (and vice versa if you're decrementing the end index). Iterating over the buffer is just a matter of starting at the start and finishing at the end, wrapping where necessary.

Now it's not clear whether you want one circular buffer per stock ticker, one overall, or some hybrid model. If you could tell us more about what you're trying to achieve, that would really help.


If i understand what you're trying to do correctly, you want the index to indicate how many ticks in the past the data is. In that case, you want to use a List<> and do this to add a new element:

List<double> priceHistory = new List<double>
...
priceHistory.insert(newprice,0)
if (priceHistory.Count == 10001) 
{
    priceHistory.removeAt(10000);
}

I do not know the performance implications of this, however i suspect its quite expensive. You could also just use a standard list and have a head pointer and do math on the index, but its a little more convoluted in terms of code readability (but probably much more efficient)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜