從原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>");