// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace System.Linq { public static partial class EnumerableEx { /// /// Creates an enumerable sequence based on an enumerator factory function. /// /// Result sequence element type. /// Enumerator factory function. /// Sequence that will invoke the enumerator factory upon a call to GetEnumerator. public static IEnumerable Create(Func> getEnumerator) { if (getEnumerator == null) throw new ArgumentNullException(nameof(getEnumerator)); return new AnonymousEnumerable(getEnumerator); } /// /// Creates an enumerable sequence based on an asynchronous method that provides a yielder. /// /// Result sequence element type. /// /// Delegate implementing an asynchronous method that can use the specified yielder to yield return /// values. /// /// Sequence that will use the asynchronous method to obtain its elements. public static IEnumerable Create(Action> create) { if (create == null) throw new ArgumentNullException(nameof(create)); foreach (var x in new Yielder(create)) yield return x; } private class AnonymousEnumerable : IEnumerable { private readonly Func> _getEnumerator; public AnonymousEnumerable(Func> getEnumerator) { _getEnumerator = getEnumerator; } public IEnumerator GetEnumerator() { return _getEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } } }