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

提供: MonoBook
2019年11月26日 (火) 07:44時点におけるAdministrator (トーク | 投稿記録)による版 (ページの作成:「C#にもPHPのshuffle(&Array)のパクリが欲しい。 ググると出てきたLINQ使ったやつ。 <source lang="csharp"> public static class IEnumerabl…」)
(差分) ← 古い版 | 最新版 (差分) | 新しい版 → (差分)
ナビゲーションに移動 検索に移動

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

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

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

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

    public static class IEnumerableExtensions
    {
        public static IEnumerable<TSource> Shuffle<TSource>(this IEnumerable<TSource> source, Random random)
        {
            var copy = source.ToList();

            int count = 0;
            while (0 < (count = copy.Count))
            {
                int index = random.Next(count);
                yield return copy[index];
                copy.RemoveAt(index);
            }
        }

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