andrew4582

EnumerableExtensions - Shuffle

Feb 10th, 2013
163
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.47 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4.  
  5. public static class EnumerableExtensions {
  6.  
  7.     public static IEnumerable<TSource> Shuffle<TSource>(this IEnumerable<TSource> source) {
  8.         List<TSource> list = source.ToList();
  9.         Random random = new Random();
  10.  
  11.         for (int i = list.Count - 1; i >= 0; i--) {
  12.             int r = random.Next(i + 1);
  13.             yield return list[r];
  14.             list[r] = list[i];
  15.         }
  16.     }
  17.  
  18. }
Advertisement
Add Comment
Please, Sign In to add comment