从原List中每次随机取一项,添加到新的List中,并在原List中删除。这样重复,直到原List为空为止。
public static List<T> GetRandomList<T>(List<T> inputList) { //Copy to a array T[] copyArray = new T[inputList.Count]; inputList.CopyTo(copyArray); //Add range List<T> copyList = new List<T>(); copyList.AddRange(copyArray); //Set outputList and random List<T> outputList = new List<T>(); Random rd = new Random(DateTime.Now.Millisecond); while (copyList.Count > 0) { //Select an index and item int rdIndex = rd.Next(0, copyList.Count - 1); T remove = copyList[rdIndex]; //remove it from copyList and add it to output copyList.Remove(remove); outputList.Add(remove); } return outputList; }
用linq
List<T> l = new List<T>(); l = l.Select(a => new { a, newID = Guid.NewGuid() }).OrderBy(b => b.newID).Select(c=>c.a).ToList();
得到随机数的方法
Random r=new Random();
int n1=r.Next(); //返回非负随机整数
Response.Write(n1+"<br>");
int n2=r.Next(10); //返回一个小于所指定最大值(10)的非负随机整数
Response.Write(n2+"<br>");
int n3=r.Next()%10; //返回一人小于所指定最大值(10)的非负随机整数
Response.Write(n3+"<br>");
int n4=r.Next(1,20); //返回一个指定范围(1-20)内的随机整数
Response.Write(n4+"<br>");
double d5=r.NextDouble(); //得到一个介于0.0-1.0之间的随机整数
Response.Write(d5+"<br>");
此随笔或为自己所写、或为转载于网络。仅用于个人收集及备忘。