概要
using System.Collections.Generic; namespace Kogane { public static class SequenceJoinTupleExtensionMethods { public static (T1, T2)[] JoinTuple<T1, T2>( this T1[] self, T2[] other ) { var count = self.Length; var result = new (T1, T2)[ count ]; for ( var i = 0; i < count; i++ ) { var x = self[ i ]; var y = other[ i ]; result[ i ] = ( x, y ); } return result; } public static (T1, T2)[] JoinTuple<T1, T2>( this IReadOnlyList<T1> self, IReadOnlyList<T2> other ) { var count = self.Count; var result = new (T1, T2)[ count ]; for ( var i = 0; i < count; i++ ) { var x = self[ i ]; var y = other[ i ]; result[ i ] = ( x, y ); } return result; } } }
使用例
Before
var numbers = new[] { 1, 2, 3 }; var names = new[] { "フシギダネ", "フシギソウ", "フシギバナ" }; for ( var i = 0; i < numbers.Length; i++ ) { var number = numbers[ i ]; var name = names[ i ]; Debug.Log( $"{number}, {name}" ); }
After
var numbers = new[] { 1, 2, 3 }; var names = new[] { "フシギダネ", "フシギソウ", "フシギバナ" }; foreach ( var (number, name) in numbers.JoinTuple( names ) ) { Debug.Log( $"{number}, {name}" ); }
少しだけコードがスッキリする