コガネブログ

平日更新を目標に Unity や C#、Visual Studio、ReSharper などのゲーム開発アレコレを書いていきます

【C#】2 つの配列の要素をインデックス同士で紐付けて Tuple にまとめる拡張メソッド

概要

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}" );
}

少しだけコードがスッキリする