Lean  $LEAN_TAG$
EnumeratorExtensions.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;
17 using System.Collections.Generic;
18 
19 namespace QuantConnect.Util
20 {
21  /// <summary>
22  /// Provides convenience of linq extension methods for <see cref="IEnumerator{T}"/> types
23  /// </summary>
24  public static class EnumeratorExtensions
25  {
26  /// <summary>
27  /// Filter the enumerator using the specified predicate
28  /// </summary>
29  public static IEnumerator<T> Where<T>(this IEnumerator<T> enumerator, Func<T, bool> predicate)
30  {
31  using (enumerator)
32  {
33  while (enumerator.MoveNext())
34  {
35  if (predicate(enumerator.Current))
36  {
37  yield return enumerator.Current;
38  }
39  }
40  }
41  }
42 
43  /// <summary>
44  /// Project the enumerator using the specified selector
45  /// </summary>
46  public static IEnumerator<TResult> Select<T, TResult>(this IEnumerator<T> enumerator, Func<T, TResult> selector)
47  {
48  using (enumerator)
49  {
50  while (enumerator.MoveNext())
51  {
52  yield return selector(enumerator.Current);
53  }
54  }
55  }
56 
57  /// <summary>
58  /// Project the enumerator using the specified selector
59  /// </summary>
60  public static IEnumerator<TResult> SelectMany<T, TResult>(this IEnumerator<T> enumerator, Func<T, IEnumerator<TResult>> selector)
61  {
62  using (enumerator)
63  {
64  while (enumerator.MoveNext())
65  {
66  using (var inner = selector(enumerator.Current))
67  {
68  while (inner.MoveNext())
69  {
70  yield return inner.Current;
71  }
72  }
73  }
74  }
75  }
76  }
77 }