andrew4582

IEnumerable Shuffle

Oct 1st, 2011
265
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.35 KB | None | 0 0
  1.     public static IEnumerable<TSource> Shuffle<TSource>(this IEnumerable<TSource> source) {
  2.         List<TSource> list = source.ToList();
  3.         Random random = new Random();
  4.  
  5.         for (int i = list.Count - 1; i >= 0; i--) {
  6.             int r = random.Next(i + 1);
  7.             yield return list[r];
  8.             list[r] = list[i];
  9.         }
  10.     }
Advertisement
Add Comment
Please, Sign In to add comment