/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System.Collections; using System.Collections.Generic; using System.Linq; namespace QuantConnect.Util { /// /// Defines a list that casts the elements of a source list to a derived type. /// This is useful to avoid materializing another list after using, for example, the LINQ method. /// /// The base type of the elements in the source enumerable. /// The type to cast the elements to. public class CastingEnumerable : IReadOnlyList where TDerived : class, TBase { private IReadOnlyList _data; /// /// Gets the count of items in the enumerable. /// public int Count => _data.Count; /// /// Gets the element at the specified index. /// /// The zero-based index of the element to get. /// The element at the specified index. public TDerived this[int index] => (TDerived)_data[index]; /// /// Initializes a new instance of the class /// public CastingEnumerable(IReadOnlyList data) { _data = data; } /// /// Returns an enumerator that iterates through the collection. /// /// /// An enumerator that can be used to iterate through the collection. /// /// 1 public IEnumerator GetEnumerator() { foreach (var item in _data) { yield return (TDerived)item; } } /// /// Returns an enumerator that iterates through a collection. /// /// /// An enumerator object that can be used to iterate through the collection. /// /// 2 IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } }