C♯で配列やコレクションをシャッフルする

提供: MonoBook
ナビゲーションに移動 検索に移動

C#にもPHPのshuffle(&Array)のパクリが欲しい。

ググると出てきたLINQ使ったやつ。

    using System;
    using System.Collections.Generic;
    using System.Linq;

    public static class IEnumerableExtension
    {
        public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> collection)
        {
            return collection.OrderBy(i => Guid.NewGuid());
        }
    }


乱数生成器が指定できたほうがよくね?Randomクラスはアルゴリズムがよろしくないらしいが、シールドクラスではないのでメルセンヌ・ツイスタあたりを実装すればいい。

    using System;
    using System.Collections.Generic;
    using System.Linq;

    public static class IEnumerableExtension
    {
        public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> collection, Random random)
        {
            return collection.OrderBy(i => random.Next());
        }

        public static IEnumerable<TSource> Shuffle<TSource>(this IEnumerable<TSource> source)
        {
            return source.Shuffle<TSource>(new Random());
        }
    }

関連項目[編集 | ソースを編集]