From 5f8e7214c6b2db25a2df24d7c9f27612091b8701 Mon Sep 17 00:00:00 2001 From: Sam Harwell Date: Wed, 31 Jan 2024 12:42:49 -0600 Subject: [PATCH] Provide overloads to avoid unnecessary boxing --- .../Collections/ImmutableArrayExtensions.cs | 46 +++++++++++++++++-- 1 file changed, 43 insertions(+), 3 deletions(-) diff --git a/src/Compilers/Core/Portable/Collections/ImmutableArrayExtensions.cs b/src/Compilers/Core/Portable/Collections/ImmutableArrayExtensions.cs index 2d518e4c11205..7159f9415f9cf 100644 --- a/src/Compilers/Core/Portable/Collections/ImmutableArrayExtensions.cs +++ b/src/Compilers/Core/Portable/Collections/ImmutableArrayExtensions.cs @@ -276,6 +276,26 @@ public static ImmutableArray SelectManyAsArray(this Imm return builder.ToImmutableAndFree(); } + /// + /// Maps and flattens a subset of immutable array to another immutable array. + /// + /// Type of the source array items + /// Type of the transformed array items + /// The array to transform + /// A transform function to apply to each element. + /// If the array's length is 0, this will return an empty immutable array. + public static ImmutableArray SelectManyAsArray(this ImmutableArray array, Func> selector) + { + if (array.Length == 0) + return ImmutableArray.Empty; + + var builder = ArrayBuilder.GetInstance(); + foreach (var item in array) + builder.AddRange(selector(item)); + + return builder.ToImmutableAndFree(); + } + /// /// Maps and flattens a subset of immutable array to another immutable array. /// @@ -288,17 +308,37 @@ public static ImmutableArray SelectManyAsArray(this Imm public static ImmutableArray SelectManyAsArray(this ImmutableArray array, Func predicate, Func> selector) { if (array.Length == 0) - { return ImmutableArray.Empty; + + var builder = ArrayBuilder.GetInstance(); + foreach (var item in array) + { + if (predicate(item)) + builder.AddRange(selector(item)); } + return builder.ToImmutableAndFree(); + } + + /// + /// Maps and flattens a subset of immutable array to another immutable array. + /// + /// Type of the source array items + /// Type of the transformed array items + /// The array to transform + /// The condition to use for filtering the array content. + /// A transform function to apply to each element that is not filtered out by . + /// If the items's length is 0, this will return an empty immutable array. + public static ImmutableArray SelectManyAsArray(this ImmutableArray array, Func predicate, Func> selector) + { + if (array.Length == 0) + return ImmutableArray.Empty; + var builder = ArrayBuilder.GetInstance(); foreach (var item in array) { if (predicate(item)) - { builder.AddRange(selector(item)); - } } return builder.ToImmutableAndFree();