一个随机列表项算法

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

public static class EnumerableExtensions {

    public static IEnumerable<TSource> Shuffle<TSource>(this IEnumerable<TSource> source) {
        List<TSource> list = source.ToList();
        Random random = new Random();

        for (int i = list.Count - 1; i >= 0; i--) {
            int r = random.Next(i + 1);
            yield return list[r];
            list[r] = list[i];
        }
    }

}
posted @ 2010-11-10 09:54  Ants  阅读(327)  评论(0编辑  收藏  举报