Home | Contact Us

CSharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript

C# Randomize Chars in String

This C# article shows how to randomize strings with LINQ. It discusses the problems with this approach.

Randomize chars in string.

This method randomly rearranges the letters in a string. It shuffles the letters for a word game or other simple application. It can help find new hash codes from the same string. This implementation can be adapted to other problems.

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.

Random Number

C# program that randomizes strings

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: senators
rand: tossenar

We see that char arrays are enumerable, meaning when you apply foreach or OrderBy, you individually get each letter. This is just what we need. This is the LINQ method syntax, which combines the OrderBy with a lambda expression.

OrderByLambda Expression

Also: You could use the query syntax instead. This is clearer in some program contexts.


Finally: ToArray converts the enumerable letters in the statement to a string again, producing the final result: a randomized string.

ToArrayString Constructor

Summary. We used OrderBy to randomize the characters in a string. This style of code could be used in much more serious systems. It is interesting to experiment with, but also has some drawbacks—it does not randomize as well as other algorithms.