コガネブログ

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

【C#】配列内の要素を複数キーでソートする拡張メソッド

ソースコード

using System;
using System.Collections.ObjectModel;

public static class ArrayExtensions
{
    /// <summary>
    /// 配列内の要素を複数キーでソートします
    /// </summary>
    public static void Sort<TSource, TResult>( 
        this TSource[] array, 
        Func<TSource, TResult> selector1, 
        Func<TSource, TResult> selector2 ) where TResult : IComparable
    {
        Array.Sort( array, ( x, y ) => 
        {
            var result = selector1( x ).CompareTo( selector1( y ) );
            return result != 0 ? result : selector2( x ).CompareTo( selector2( y ) );
        } );
    }
}

使い方

class Pokemon
{
    public int      mNumber;    // 番号
    public string   mName;      // ポケモン名
    public int      mStatus;    // 強さ

    public Pokemon( int number, string name, int status )
    {
        mNumber = number;
        mName   = name;
        mStatus = status;
    }
}

private void Awake()
{
    // ポケモンのデータを管理する配列を作成します
    var pokemonList = new []
    {
        new Pokemon( 150, "メガミュウツーX",  780 ), 
        new Pokemon( 150, "メガミュウツーY",  780 ),  
        new Pokemon( 373, "メガボーマンダ",   700 ),  
        new Pokemon( 376, "メガメタグロス",   700 ),  
        new Pokemon( 382, "ゲンシカイオーガ", 770 ),  
        new Pokemon( 380, "メガラティアス",   700 ),  
        new Pokemon( 381, "メガラティオス",   700 ),  
        new Pokemon( 383, "ゲンシグラードン", 770 ),  
        new Pokemon( 384, "メガレックウザ",   780 ),  
        new Pokemon( 493, "アルセウス",       720 ),  
    };

    // ポケモンのデータを強さ順でソートした後に番号順にソートします
    pokemonList.Sort( c => c.mStatus, c => c.mNumber );
}

LINQのOrderBy関数とThenBy関数を使用することで同様の処理を実装可能ですが
UnityでiOSのアプリを作成する場合、iOSではThenBy関数が使えないので作成しました

参考サイト様

Unity+iOSでエラーになるLINQのまとめ - Qiita
neue cc - Unity + iOSのAOTでの例外の発生パターンと対処法

関連記事