microsoft/healthcare-shared-components
Publicmirrored from https://github.com/microsoft/healthcare-shared-componentsAvailable
src/Microsoft.Health.Core/Extensions/EnumerableExtensions.cs
45lines · modecode
| 1 | // ------------------------------------------------------------------------------------------------- |
| 2 | // Copyright (c) Microsoft Corporation. All rights reserved. |
| 3 | // Licensed under the MIT License (MIT). See LICENSE in the repo root for license information. |
| 4 | // ------------------------------------------------------------------------------------------------- |
| 5 | |
| 6 | using System.Collections.Generic; |
| 7 | using System.Linq; |
| 8 | using EnsureThat; |
| 9 | |
| 10 | namespace Microsoft.Health.Core.Extensions |
| 11 | { |
| 12 | public static class EnumerableExtensions |
| 13 | { |
| 14 | /// <summary> |
| 15 | /// Creates the cartesian product. |
| 16 | /// </summary> |
| 17 | /// <typeparam name="TSource">The type of the elements of the input sequences.</typeparam> |
| 18 | /// <param name="sequences">The input sequence.</param> |
| 19 | /// <returns>An <see cref="IEnumerable{T}"/> that contains the cartesian product of the input sequences.</returns> |
| 20 | public static IEnumerable<IEnumerable<TSource>> CartesianProduct<TSource>(this IEnumerable<IEnumerable<TSource>> sequences) |
| 21 | { |
| 22 | EnsureArg.IsNotNull(sequences, nameof(sequences)); |
| 23 | |
| 24 | IEnumerable<IEnumerable<TSource>> emptyProduct = new[] { Enumerable.Empty<TSource>() }; |
| 25 | |
| 26 | return sequences.Aggregate( |
| 27 | emptyProduct, |
| 28 | (accumulator, sequence) => |
| 29 | { |
| 30 | return accumulator.SelectMany(a => sequence.Select(s => a.Concat(Enumerable.Repeat(s, 1)))); |
| 31 | }); |
| 32 | } |
| 33 | |
| 34 | /// <summary> |
| 35 | /// Generates a sequence that contains one value. |
| 36 | /// </summary> |
| 37 | /// <typeparam name="TResult">The element type.</typeparam> |
| 38 | /// <param name="element">The element to return.</param> |
| 39 | /// <returns>An <see cref="IEnumerable{T}"/> that contains one value.</returns> |
| 40 | public static IEnumerable<TResult> AsEnumerable<TResult>(this TResult element) |
| 41 | { |
| 42 | yield return element; |
| 43 | } |
| 44 | } |
| 45 | } |