C#

Fools ignore complexity; pragmatists suffer it; experts avoid it; CREATIVES remove it.

Tuesday, November 19, 2013

Shuffle C# List



Long time without posting. 

Too many things happened in my life during that time but it's not topic for this blog, then,
what about code this time? 



Simple put, I needed shuffle a simple List in C# and I was not able to find some easy way over the internet, so I spent some minutes to create my own way, a small handly function to shuffle IList, use it, enjoy it and improve it (in this case, just let me know how to do it better).

long life and stay creative!

    void Shuffle<T>(ref List<Tt)
    {
        //create a temporary empty list
        List<Ttmp = new List<T>();
        
        System.Random rand = new System.Random();
        
        //create a temporary index list
        List<intindexList = new List<int>();
        for (int j = 0j < t.Count; ++j)
            indexList.Add(j);
        
        while (indexList.Count > 0)
        {
            int k = rand.Next(0indexList.Count - 1);
            // Console.WriteLine("index: " + indexList[k] + " content: " + t[indexList[k]]);
            tmp.Add(t[indexList[k]]);
            indexList.RemoveAt(k);

            tmp.Reverse ();
        }

        
        t = new List<T>(tmp);
        
        return;
    }

No comments: