Build an extension to repeat and shuffle any collection (this one uses Fisher-Yates)
public static class EnumerableExtensions
{
private static readonly Random _rng = new Random();
public static IEnumerable<T> Shuffle<T>( this IEnumerable<T> collection, Random rng = null )
{
rng = rng ?? _rng;
var list = collection.ToList();
for (int i = 0; i < list.Count; i++)
{
var j = i + rng.Next( list.Count - i );
yield return list[j];
if (i != j)
{
list[j] = list[i];
}
}
}
public static IEnumerable<T> Repeat<T>(this IEnumerable<T> collection, int count)
{
for ( int i = 0; i < count; i++ )
{
foreach ( var item in collection )
{
yield return item;
}
}
}
}
and use it like
string[] fruits = new string[] { "Apple", "Banana", "Orange" };
string[] basket = fruits
.Repeat( ( 20 + fruits.Length - 1 ) / fruits.Length )
.Shuffle()
.Take( 20 )
.ToArray();
More random can be achieved by
public static class EnumerableExtensions
{
...
public static IEnumerable<T> RandomRepeat<T>(this IEnumerable<T> collection, int count, Random rng = null)
{
rng = rng ?? _rng;
var list = collection.ToList();
for ( int i = 0; i < count; i++ )
{
var j = rng.Next( list.Count );
yield return list[j];
}
}
}
and
string[] fruits = new string[] { "Apple", "Banana", "Orange" };
string[] basket = fruits.RandomRepeat( 20 ).ToArray();