Proposal: Add IEnumerable
extensions for "unzipping"
#91803
-
.NET has a method to "zip" I propose an "unzip" operation that would do such a thing. These methods would take an A use case of these could be to take an IEnumerable<(decimal X, decimal Y)> points = ...
(decimal X, decimal Y)[] pointsAsArray = points.ToArray(); // required to avoid multiple enumeration below
decimal[] xValues = pointsAsArray.Select(tuple => tuple.X).ToArray();
decimal[] yValues = pointsAsArray.Select(tuple => tuple.Y).ToArray(); The "unzip" methods would bypass the collection step above: IEnumerable<(decimal X, decimal Y)> points = ...
(IEnumerable<decimal> xValuesEnumerable, IEnumerable<decimal> yValuesEnumerable) = points.Unzip();
decimal[] xValues = xValuesEnumerable.ToArray();
decimal[] yValues = yValuesEnumerable.ToArray(); As mentioned above, "unzip to array" and "unzip to list" convenience methods would be provided to simplify the extra "collect" steps after unziping: IEnumerable<(decimal X, decimal Y)> points = ...
(decimal[] xValues, decimal[] yValues) = points.UnzipToArray(); The API would be as follows: using System.Collections.Generic;
namespace System.Linq;
public static class Enumerable
{
public static (IEnumerable<TFirst> First, IEnumerable<TSecond> Second) Unzip<TFirst, TSecond>(
this IEnumerable<(TFirst, TSecond)> source);
public static (IEnumerable<TFirst> First, IEnumerable<TSecond> Second, IEnumerable<TThird> Third) Unzip<TFirst, TSecond, TThird>(
this IEnumerable<(TFirst, TSecond, TThird)> source);
// could also be `UnzipToArrays`
public static (TFirst[] First, TSecond[] Second) UnzipToArray<TFirst, TSecond>(
this IEnumerable<(TFirst, TSecond)> source);
public static (TFirst[] First, TSecond[] Second, TThird[] Third) UnzipToArray<TFirst, TSecond, TThird>(
this IEnumerable<(TFirst, TSecond, TThird)> source);
// could also be `UnzipToLists`
public static (List<TFirst> First, List<TSecond> Second) UnzipToList<TFirst, TSecond>(
this IEnumerable<(TFirst, TSecond)> source);
public static (List<TFirst> First, List<TSecond> Second, List<TThird> Third) UnzipToList<TFirst, TSecond, TThird>(
this IEnumerable<(TFirst, TSecond, TThird)> source);
} Only two- and three-tuple methods are proposed, but more could be added. I was just following the fact that |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Forgot that API proposals go in "issues" on the runtime repo. Added one with #91804. |
Beta Was this translation helpful? Give feedback.
Forgot that API proposals go in "issues" on the runtime repo. Added one with #91804.