Get Random Selection from IEnumerable - CSharp System.Collections

CSharp examples for System.Collections:IEnumerable

Description

Get Random Selection from IEnumerable

Demo Code


using System.Linq;
using System.Collections.Generic;
using System.Collections;
using System;/*  ww w.ja va2s  .co  m*/

public class Main{
        public static IEnumerable<T> GetRandomSelection<T>(this IEnumerable<T> array, int count = 1)
        {
            //Determine the max length of our incoming array
            var maxLength = array.Count();

            //Create a new list to contain our selection...
            var randomSelection = new List<T>();

            for (var i = 0; i < count; i++)
            {
                var randomInterval = R.Next(0, maxLength);
                randomSelection.Add(array.ElementAt(randomInterval));
            }

            return randomSelection;
        }
}

Related Tutorials