Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,971 questions

51,913 answers

573 users

How to randomize (shuffle) an array of strings in C#

2 Answers

0 votes
using System;

class Program
{
   static Random _random = new Random();
 
    // Fisher-Yates shuffle
    static void Shuffle<T>(T[] array) {
        int n = array.Length;
        
        for (int i = 0; i < n; i++) {
            int rand = i + _random.Next(n - i);
            T temp = array[rand];
            array[rand] = array[i];
            array[i] = temp;
        }
    }

    static void Main()
    {
       string[] array = { "c#", "c", "c++", "go", "java", "php", "rust" };
 
        Shuffle(array);
        
        foreach (string s in array) {
            Console.Write("{0} ", s);
        }
    }
}

 
 
/*
run:
 
c c++ go c# php rust java 
 
*/

 



answered Aug 25, 2018 by avibootz
edited Jun 1, 2025 by avibootz
0 votes
using System;
using System.Linq;
using System.Collections.Generic;
 
class Program
{
    static Random _random = new Random();
 
    static string[] ShuffleArray(string[] arr) {
        List<KeyValuePair<int, string>> list = new List<KeyValuePair<int, string>>();
 
        foreach (string s in arr) {
            list.Add(new KeyValuePair<int, string>(_random.Next(), s));
        }
 
        var sorted = from item in list
                     orderby item.Key
                     select item;
 
        string[] shuffled = new string[arr.Length];
 
        int i = 0;
        foreach (KeyValuePair<int, string> pair in sorted) {
            shuffled[i++] = pair.Value;
        }
 
        return shuffled;
    }
 
    static void Main(string[] args)
    {
        string[] arr = new string[]
        {
            "c#",
            "c",
            "c++",
            "go",
            "java",
            "python",
            "rust",
        };
             
        string[] shuffledArr = ShuffleArray(arr);
 
        foreach (string s in shuffledArr) {
            Console.WriteLine(s);
        }
    }
}

 
/*
run:
 
c++
rust
c#
python
c
go
java
 
*/

 



answered Jun 1, 2025 by avibootz

Related questions

1 answer 91 views
91 views asked Jun 30, 2023 by avibootz
1 answer 144 views
144 views asked Oct 30, 2021 by avibootz
2 answers 126 views
1 answer 144 views
1 answer 143 views
...