Home Linq - Three-way Zip
Post
Cancel

Linq - Three-way Zip

.NET 6 introduces an overload allowing a third argument for the Zip() extension method on System.Linq namespace. formerly, only 2 Enumerables were allowed. In summary, it will produce a sequence of tuples with elements from the three specified sequences.

IEnumerable<(TFirst First, TSecond Second, TThird Third)> Zip<TFirst, TSecond, TThird>(this IEnumerable<TFirst> first, IEnumerable<TSecond> second, IEnumerable<TThird> third)


Hands-On


I have written an example using the three arguments of Zip() to print a summary resulting from the three given Enumerable.

Notice that in the example, Zip() will return an IEnumerable<(string, int, Probe)>, hence when iterating through the generated tuple, you have to respect the types accordingly:

foreach ((string first, int second, Probe third) in planetsNames.Zip(planetsMoons, planetsProbes))


DateOnly and TimeOnly structs

Since I’ve used the DateOnly type with the Probe model, I think it’s worth mentioning these new types.

readonly struct DateOnly : IComparable, IComparable<DateOnly>, IEquatable<DateOnly>, ISpanFormattable, IFormattable
readonly struct TimeOnly : IComparable, IComparable<TimeOnly>, IEquatable<TimeOnly>, ISpanFormattable, IFormattable

DateOnly and TimeOnly struct types are very handy additions to .NET 6 on System namespace. The TimeOnlyis intended to represent only the time of a day, while the DateOnly, which I used with the example above, represents only a date. You can learn more about the possibilities with both on the linked official documentation.

To know more about the usage of struct types, please check my previous post.


Check the project on GitHub



This post is licensed under CC BY 4.0 by the author.