A function to Shuffle Array and List using C#


Below is a function that shuffles an array or a list. It accepts a list or array to be shuffled/rearranged as an argument and returns a shuffled copy of the object passed.

        public E ShuffleArrayAndList<E>(IList<E> arr)
        {
            Random random = new Random();
            E result = arr[arr.Count];
            E tmpArray = arr[arr.Count];
            if (arr.Count > 1)
            {
                for (int i = arr.Count - 1; i >= 0; i--)
                {

                    int randomIndex = random.Next(i + 1);
                    arr[i] = arr[randomIndex];
                    arr[randomIndex] = tmpArray;
                }

            }
            result = tmpArray;
            return result;
        }

More C# Snippets

Tutorials Panel

About Tutorials Panel

programming tutorial and source code for Software Engineers and developers. https://twitter.com/TutorialsPanel

View all posts by Tutorials Panel →