C# Randomize Chars in String

String type

You want to randomly rearrange the letters in your C# string. This will shuffle the letters for a word game or other simple application, and can help find new hashes from the same string.

This C# article shows how you can randomize strings with LINQ.

Example

First, this solution uses LINQ and the method syntax. This is not a cryptographic or casino-quality algorithm, but for quick applications, it works great. It uses OrderBy along with the new string constructor.

Program that randomizes strings [C#]

using System;
using System.Linq;

class Program
{
    static void Main()
    {
	// The source string
	const string original = "senators";

	// The random number sequence
	Random num = new Random();

	// Create new string from the reordered char array
	string rand = new string(original.ToCharArray().
	    OrderBy(s => (num.Next(2) % 2) == 0).ToArray());

	// Write results
	Console.WriteLine("original: {0}\r\nrand: {1}",
	    original,
	    rand);
	Console.Read();
    }
}

Output

original: senators
rand: tossenar
LINQ (language integrated query)

Note. The important point are that char arrays in C# are enumerable, meaning when you apply foreach or OrderBy, you get each letter individually, which is just what we need. This is an example of the LINQ method syntax, which combines the OrderBy with a lambda expression. You could use the query syntax instead. Finally, ToArray() converts the enumerable letters in the statement to a string again, producing the final result: a randomized string.

Summary

In this article, we saw an example of how you can use OrderBy to randomize the results. This style of code could be used in much more serious systems, and it is interesting to experiment with.

Algorithms
.NET