首先抛出个问题,怎么获得一个既安全有效,又方便调用的乱序List呢?
其实代码很简单,但又非常有意思,如下所示:
using System;
using System.Text;
using System.Threading;
using System.Collections.Generic;
public static class ThreadSafeRandom
{
[ThreadStatic]
private static Random Local;
public static Random ThreadsRandom
{
get
{
return Local ?? (Local = new Random(unchecked(Environment.TickCount * 31 + Thread.CurrentThread.ManagedThreadId)));
}
}
}
public static class Extensions
{
public static void Shuffle<T>(this IList<T> list)
{
int n = list.Count;
while (n > 1)
{
n--;
int k = ThreadSafeRandom.ThreadsRandom.Next(n + 1);
T value = list[k];
list[k] = list[n];
list[n] = value;
}
}
public static void Clear(this StringBuilder value)
{
value.Length = 0;
value.Capacity = 0;
value.Capacity = 16;
}
}
因为是Extensions方法,只要如下这么调用即可:
List<T> list = new List<T>();
list.Shuffle();
这样就可以list里的数据就可是随机乱序的了,是不是很简单呢?