C# — Shuffle a String in One Line

 

Need to randomly shuffle the characters of a string? Most people would loop and swap, but here’s a LINQ one-liner:
using System; using System.Linq; class Program { static void Main() { string text = "HELLOWORLD"; // Shuffle the string in one line string shuffled = new string(text.OrderBy(_ => Guid.NewGuid()).ToArray()); Console.WriteLine($"Shuffled: {shuffled}"); } }

What’s cool about it?

  • Uses OrderBy with Guid.NewGuid() for randomness.

  • No loops or manual swaps needed.

  • Works with any string—names, codes, even emojis.


🧩 Curiosity twist: Shuffle words instead of characters!

string sentence = "C# makes coding fun and expressive"; string shuffledWords = string.Join(" ", sentence.Split(' ').OrderBy(_ => Guid.NewGuid()) ); Console.WriteLine(shuffledWords);

Example output:

expressive coding and C# fun makes

✍️ Written by Luis Fernandez Leyva, Software Engineer

Comments

Popular posts from this blog

About Me

3. C# — Get Unique Characters in One Line

C# — Generate a Random String in One Line