コガネブログ

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

【C#】List を指定されたパラメータでソートできるようにする拡張メソッド

ソースコード

using System;
using System.Collections.Generic;

public static class ListExtensions
{
    public static void Sort<TSource, TResult>( 
        this List<TSource> self, 
        Func<TSource, TResult> selector
    ) where TResult : IComparable
    {
        self.Sort( ( x, y ) => selector( x ).CompareTo( selector( y ) ) );
    }
}

使い方

public class Character
{
    public int Id;
}

private void Awake()
{
    var list = new List<Character>
    {
        new Character{ Id = 3 }, 
        new Character{ Id = 1 }, 
        new Character{ Id = 2 }, 
    };
    list.Sort( c => c.Id );
    list.ForEach( c => Debug.Log( c.Id ) );
    // 1
    // 2
    // 3
}

関連記事