Lean  $LEAN_TAG$
FixedSizeQueue.cs
1 /*
2  * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
3  * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14 */
15 
16 using System.Collections.Generic;
17 
18 namespace QuantConnect.Util
19 {
20  /// <summary>
21  /// Helper method for a limited length queue which self-removes the extra elements.
22  /// http://stackoverflow.com/questions/5852863/fixed-size-queue-which-automatically-dequeues-old-values-upon-new-enques
23  /// </summary>
24  /// <typeparam name="T">The type of item the queue holds</typeparam>
25  public class FixedSizeQueue<T> : Queue<T>
26  {
27  private int _limit = -1;
28 
29  /// <summary>
30  /// Max Length
31  /// </summary>
32  public int Limit
33  {
34  get { return _limit; }
35  set { _limit = value; }
36  }
37 
38  /// <summary>
39  /// Create a new fixed length queue:
40  /// </summary>
41  public FixedSizeQueue(int limit)
42  : base(limit)
43  {
44  Limit = limit;
45  }
46 
47  /// <summary>
48  /// Enqueue a new item int the generic fixed length queue:
49  /// </summary>
50  public new void Enqueue(T item)
51  {
52  while (Count >= Limit)
53  {
54  Dequeue();
55  }
56  base.Enqueue(item);
57  }
58  }
59 }