Randomly rearrange a string in .NET C#

Say you’d like to randomly rearrange the contents of a string, i.e. put the constituent characters into new, random positions. The following method can help you with that using a combination of LINQ and Random:

private static string RearrangeString(string startingPoint)
{
	Random num = new Random();
	string rand = new string(startingPoint.
		OrderBy(s => (num.Next(2) % 2) == 0).ToArray());
	return rand;
}

Let’s test it with my name:

string myName = "Andras Nemes";
string myNewName = RearrangeString(myName);

So my new name can be something like “drsNeeAna ms” or “AdaNmesnrs e” or even “ArsNmenda es”, I haven’t decided yet.

Filip Ekberg drew my attention to the following alternative solution:

string rand = new string(startingPoint.OrderBy(x => Guid.NewGuid()).ToArray());

View the list of posts on LINQ here.

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

Leave a comment

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.