构建一个扩展来重复和随机播放 any 集合(这个使用Fisher-Yates)
public static class EnumerableExtensions
{
private static readonly Random _rng = new Random();
public static IEnumerable Shuffle( this IEnumerable 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 Repeat(this IEnumerable collection, int count)
{
for ( int i = 0; i < count; i++ )
{
foreach ( var item in collection )
{
yield return item;
}
}
}
}
并使用它
string[] fruits = new string[] { "Apple", "Banana", "Orange" };
string[] basket = fruits
.Repeat( ( 20 + fruits.Length - 1 ) / fruits.Length )
.Shuffle()
.Take( 20 )
.ToArray();
可以通过实现更随机的方式
public static class EnumerableExtensions
{
...
public static IEnumerable RandomRepeat(this IEnumerable 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];
}
}
}
和
string[] fruits = new string[] { "Apple", "Banana", "Orange" };
string[] basket = fruits.RandomRepeat( 20 ).ToArray();