首先拋出個(gè)問(wèn)題屡久,怎么獲得一個(gè)既安全有效,又方便調(diào)用的亂序List呢爱榔?
其實(shí)代碼很簡(jiǎn)單被环,但又非常有意思,如下所示:
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;
}
}
因?yàn)槭荅xtensions方法详幽,只要如下這么調(diào)用即可:
List<T> list = new List<T>();
list.Shuffle();
這樣就可以list里的數(shù)據(jù)就可是隨機(jī)亂序的了筛欢,是不是很簡(jiǎn)單呢?