Random random = new Random(); List<Content> newList = new List<Content>(); foreach (Content item in ContentList) { newList.Insert(random.Next(newList.Count), item); } return newList;
可以用linq试试Random rnd = new ...;var q =from n in numbers order by rnd.Next() select n;result = q.ToList(); 胡写的,没测试,行不行不知道
using System;class Program { static void Main() { int[] array = new int[]{ 1,1,2,2,3,3,4,4 }; byte[] keys = new byte[array.Length]; new Random().NextBytes(keys); Array.Sort(keys, array); // <---- 这样就 OK 了! foreach (int x in array) Console.WriteLine(x); } }
//个人想法,仅供参考 //效率不高,简明易懂 using System; namespace ConsoleApplication5 { class Program { static void Main(string[] args) { int[] arr = { 1, 1, 2, 2, 3, 3, 4, 4 }; int[] index = GetRandom(arr.Length-1, arr.Length-1); for (int i = 0; i < index.Length; i++) { Console.WriteLine(arr[index[i]]); } Console.ReadKey(); } /// <summary> /// 获取不重复的随机数 /// </summary> /// <param name="max">产生随机数的范围0-max</param> /// <param name="amount">要产生多少个</param> /// <returns></returns> static int[] GetRandom(int max, int amount) { int[] seed = new int[max]; int[] result = new int[amount]; int id; Random random = new Random(); for (int i = 0; i < seed.Length; i++) { seed[i] = i + 1;//用不重复数字装填原始数组 } for (int j = 0; j < amount; j++) { id = random.Next(0, max); //在随机位置取出一个数,保存到结果数组 result[j] = seed[id]; //最后一个数复制到当前位置 seed[id] = seed[max - 1]; //位置的下限减少一 max--; } return result; } } }
List<Content> newList = new List<Content>();
foreach (Content item in ContentList)
{
newList.Insert(random.Next(newList.Count), item);
}
return newList;
order by rnd.Next()
select n;result = q.ToList();
胡写的,没测试,行不行不知道
{
static void Main()
{
int[] array = new int[]{ 1,1,2,2,3,3,4,4 };
byte[] keys = new byte[array.Length];
new Random().NextBytes(keys);
Array.Sort(keys, array); // <---- 这样就 OK 了! foreach (int x in array)
Console.WriteLine(x);
}
}
//效率不高,简明易懂
using System;
namespace ConsoleApplication5
{
class Program
{
static void Main(string[] args)
{
int[] arr = { 1, 1, 2, 2, 3, 3, 4, 4 };
int[] index = GetRandom(arr.Length-1, arr.Length-1);
for (int i = 0; i < index.Length; i++)
{
Console.WriteLine(arr[index[i]]);
}
Console.ReadKey();
}
/// <summary>
/// 获取不重复的随机数
/// </summary>
/// <param name="max">产生随机数的范围0-max</param>
/// <param name="amount">要产生多少个</param>
/// <returns></returns>
static int[] GetRandom(int max, int amount)
{
int[] seed = new int[max];
int[] result = new int[amount];
int id;
Random random = new Random();
for (int i = 0; i < seed.Length; i++)
{
seed[i] = i + 1;//用不重复数字装填原始数组
}
for (int j = 0; j < amount; j++)
{
id = random.Next(0, max); //在随机位置取出一个数,保存到结果数组
result[j] = seed[id]; //最后一个数复制到当前位置
seed[id] = seed[max - 1]; //位置的下限减少一
max--;
}
return result;
}
}
}