Shuffle IList To New List - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:IList

Description

Shuffle IList To New List

Demo Code


using System.Linq;
using System.Text;
using System.Globalization;
using System.ComponentModel;
using System.Collections.Generic;
using System.Collections;

public class Main{
        public static List<T> ShuffleToNewList<T>(this IList<T> items, int times)
        {/*from   w  ww  .ja v a 2s . c o  m*/
            var res = new List<T>(items);
            res.ShuffleInPlace(times);
            return res;
        }
        public static List<T> ShuffleToNewList<T>(this IList<T> items)
        {
            return ShuffleToNewList(items, 4);
        }
        public static void ShuffleInPlace<T>(this IList<T> items, int times)
        {
            for (int j = 0; j < times; j++)
            {
                var rnd = new Random((int)(DateTime.Now.Ticks % int.MaxValue) - j);

                for (int i = 0; i < items.Count; i++)
                {
                    var index = rnd.Next(items.Count - 1);
                    var temp = items[index];
                    items[index] = items[i];
                    items[i] = temp;
                }
            }
        }
        public static void ShuffleInPlace<T>(this IList<T> items)
        {
            ShuffleInPlace(items, 4);
        }
}

Related Tutorials