// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT License. // See the LICENSE file in the project root for more information. using System.Collections.Generic; 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 ExpandCore(source, selector); } private static IEnumerable ExpandCore(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; } } } } }