// 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.Generic; using System.Linq; using System.Threading.Tasks; namespace System.Linq { public static partial class EnumerableEx { /// /// Expands the sequence by recursively applying a selector function. /// /// Source sequence element type. /// Source sequence. /// Selector function to retrieve the next sequence to expand. /// Sequence with results from the recursive expansion of the source sequence. public static IEnumerable Expand(this IEnumerable source, Func> selector) { if (source == null) throw new ArgumentNullException(nameof(source)); if (selector == null) throw new ArgumentNullException(nameof(selector)); return source.Expand_(selector); } private static IEnumerable Expand_(this IEnumerable source, Func> selector) { var queue = new Queue>(); queue.Enqueue(source); while (queue.Count > 0) { var src = queue.Dequeue(); foreach (var item in src) { queue.Enqueue(selector(item)); yield return item; } } } } }