突然有一个需求,要求数组中数据在返回前进行随机打乱,于是就记录下来。

方法一

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
  
public static void ListRandom<T>(List<T> sources)
{
Random rd = new Random();
int index = 0;
T temp;
for (int i = 0; i < sources.Count; i++)
{
index = rd.Next(0, sources.Count - 1);
if (index != i)
{
temp = sources[i];
sources[i] = sources[index];
sources[index] = temp;
}
}
}

方法二

1
2
3
4
5
6
7
8
9
10
public static List<T> ListRandom<T>(List<T> sources)
{
var random = new Random();
var resultList = new List<T>();
foreach (var item in sources)
{
resultList.Insert(random.Next(resultList.Count), item);
}
return resultList;
}