Randomly rearrange a string in .NET C#
February 8, 2017 Leave a comment
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.