Lean  $LEAN_TAG$
FilterEnumerator.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 
17 using System;
18 using System.Collections;
19 using System.Collections.Generic;
20 
22 {
23  /// <summary>
24  /// Enumerator that allow applying a filtering function
25  /// </summary>
26  /// <typeparam name="T"></typeparam>
27  public class FilterEnumerator<T> : IEnumerator<T>
28  {
29  private readonly IEnumerator<T> _enumerator;
30  private readonly Func<T, bool> _filter;
31 
32  /// <summary>
33  /// Creates a new instance
34  /// </summary>
35  /// <param name="enumerator">The underlying enumerator to filter on</param>
36  /// <param name="filter">The filter to apply</param>
37  public FilterEnumerator(IEnumerator<T> enumerator, Func<T, bool> filter)
38  {
39  _enumerator = enumerator;
40  _filter = filter;
41  }
42 
43  #region Implementation of IDisposable
44 
45  /// <summary>
46  /// Disposes the FilterEnumerator
47  /// </summary>
48  public void Dispose()
49  {
50  _enumerator.Dispose();
51  }
52 
53  #endregion
54 
55  #region Implementation of IEnumerator
56 
57  /// <summary>
58  /// Moves the FilterEnumerator to the next item
59  /// </summary>
60  public bool MoveNext()
61  {
62  // run the enumerator until it passes the specified filter
63  while (_enumerator.MoveNext())
64  {
65  if (_filter(_enumerator.Current))
66  {
67  return true;
68  }
69  }
70  return false;
71  }
72 
73  /// <summary>
74  /// Resets the FilterEnumerator
75  /// </summary>
76  public void Reset()
77  {
78  _enumerator.Reset();
79  }
80 
81  /// <summary>
82  /// Gets the current item in the FilterEnumerator
83  /// </summary>
84  public T Current
85  {
86  get { return _enumerator.Current; }
87  }
88 
89  object IEnumerator.Current
90  {
91  get { return _enumerator.Current; }
92  }
93 
94  #endregion
95  }
96 }