將一維數組中元素隨機打亂排序


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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM