Login Register
Code2night
  • Home
  • Blog Archive
  • Learn
    • Tutorials
    • Videos
  • Interview Q&A
  • Languages
    • Angular
    • C
    • C#
    • HTML/CSS
    • Java
    • JavaScript
    • Node.js
    • Python
    • React
    • Security
    • SQL Server
    • TypeScript
  • Post Blog
  • Tools
    • JSON Beautifier
    • HTML Beautifier
    • XML Beautifier
    • CSS Beautifier
    • JS Beautifier
    • PDF Editor
    • Word Counter
    • Base64 Encode/Decode
    • Diff Checker
    • JSON to CSV
    • Password Generator
    • SEO Analyzer
    • Background Remover
  1. Home
  2. Blog
  3. C#
  4. How to shuffle list in c#

How to shuffle list in c#

Date- May 14,2022

Updated Feb 2026

6245

C#Net AspNet

Understanding the Need for Shuffling

Shuffling a list is a common requirement in many applications. Whether you are developing a card game, displaying random quotes, or selecting random items from a list, you may want to ensure that the order of items is unpredictable. The Random class in C# offers a straightforward way to achieve this.

For example, consider a scenario where you have a list of trivia questions. If the questions are always presented in the same order, users may memorize them, reducing the challenge. Shuffling the list ensures that users face different questions each time they engage with your application.

Prerequisites

Before diving into the code, make sure you have a basic understanding of C# and .NET framework. Familiarity with collections, especially lists, will be beneficial. You should have a development environment set up, such as Visual Studio or Visual Studio Code, to run the examples provided.

Shuffling a List Using the Random Class

One of the simplest ways to shuffle a list in C# is by using the Random class. The approach involves generating a random number for each element and ordering the list based on these random numbers.

using System;
using System.Collections.Generic;
using System.Linq;

class Author {
    public string Name { get; set; }
    public string Book { get; set; }
    public double Price { get; set; }
}

class Program {
    static void Main() {
        List<Author> authors = new List<Author> {
            new Author { Name = "Code", Book = "C# Programming", Price = 59.95 },
            new Author { Name = "Code2Night", Book = "Shuffle", Price = 69.95 },
            new Author { Name = "Blogs", Book = "Lists", Price = 79.95 }
        };
        Random rnd = new Random();
        authors = authors.OrderBy(item => rnd.Next()).ToList();

        foreach (var author in authors) {
            Console.WriteLine($"{author.Name} - {author.Book} - ${author.Price}");
        }
    }
}

In this example, we create a list of Author objects and use the OrderBy method along with Random to shuffle the list. Each time you run the program, the order of the authors will change.

Alternative Method: Fisher-Yates Shuffle

While using the Random class is effective, the Fisher-Yates shuffle algorithm provides a more efficient and straightforward way to shuffle a list in place. This algorithm ensures that every permutation of the list is equally likely.

using System;
using System.Collections.Generic;

class Program {
    static void Main() {
        List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        Shuffle(numbers);

        foreach (var number in numbers) {
            Console.WriteLine(number);
        }
    }

    static void Shuffle<T>(List<T> list) {
        Random rnd = new Random();
        int n = list.Count;
        for (int i = n - 1; i > 0; i--) {
            int j = rnd.Next(0, i + 1);
            // Swap
            T temp = list[i];
            list[i] = list[j];
            list[j] = temp;
        }
    }
}

This function iterates over the list from the last element to the first, swapping each element with a randomly selected element that comes before it (including itself). This method is efficient and modifies the original list directly.

Edge Cases & Gotchas

When working with randomization and shuffling, there are a few edge cases and gotchas to keep in mind:

  • Empty Lists: Ensure your shuffle method can handle empty lists gracefully without throwing exceptions.
  • Single Element Lists: Shuffling a list with only one element should return the same list, as there's no other element to shuffle with.
  • Random Seed Variation: If you instantiate the Random class multiple times in a short duration, it may produce the same sequence of numbers. To avoid this, create a single instance and reuse it.

Performance & Best Practices

When shuffling a list, performance can vary based on the size of the list and the algorithm used. The Fisher-Yates shuffle is generally more efficient than using OrderBy with a random number generator, especially for larger lists.

Here are some best practices to consider:

  • Reuse Random Instances: As mentioned earlier, create a single instance of the Random class and reuse it to avoid issues with the random number sequence.
  • Use Generics for Flexibility: Implement the shuffle function as a generic method so that it can work with any type of list, not just integers or authors.
  • Test Your Shuffle: Always validate that your shuffle method produces a uniform distribution. You can do this by testing the output over a large number of iterations.

Conclusion

Shuffling a list in C# can be accomplished using different methods, each with its advantages and use cases. The Random class provides a simple way to shuffle lists, while the Fisher-Yates algorithm is a more efficient option.

Key Takeaways:

  • Shuffling is essential for various applications where unpredictability is required.
  • The Fisher-Yates shuffle is generally preferred for its efficiency and simplicity.
  • Always consider edge cases and best practices when implementing shuffling algorithms.

S
Shubham Batra
Programming author at Code2Night โ€” sharing tutorials on ASP.NET, C#, and more.
View all posts โ†’

Related Articles

Get random number in asp.net C#
Dec 23, 2023
Understanding Call By Reference in C#: A Complete Guide
Dec 09, 2023
How to Use Stored Procedures with Parameters in Dapper
Jan 23, 2024
Mastering LINQ in C#: A Complete Guide with Examples
Dec 09, 2023
Previous in C#
Zoom C# Wrapper Integration
Next in C#
How to Convert DataTable to List

Comments

Contents

๐ŸŽฏ

Interview Prep

Ace your C# interview with curated Q&As for all levels.

View C# Interview Q&As

More in C#

  • Zoom C# Wrapper Integration 12893 views
  • Convert HTML String To Image In C# 11450 views
  • The report definition is not valid or is not supported by th… 10790 views
  • Replacing Accent Characters with Alphabet Characters in CSha… 9744 views
  • Get IP address using c# 8608 views
View all C# posts โ†’

Tags

AspNet C# programming AspNet MVC c programming AspNet Core C software development tutorial MVC memory management Paypal coding coding best practices data structures programming tutorial tutorials object oriented programming Slick Slider StripeNet
Free Download for Youtube Subscribers!

First click on Subscribe Now and then subscribe the channel and come back here.
Then Click on "Verify and Download" button for download link

Subscribe Now | 1760
Download
Support Us....!

Please Subscribe to support us

Thank you for Downloading....!

Please Subscribe to support us

Continue with Downloading
Be a Member
Join Us On Whatsapp
Code2Night

A community platform for sharing programming knowledge, tutorials, and blogs. Learn, write, and grow with developers worldwide.

Panipat, Haryana, India
info@code2night.com
Quick Links
  • Home
  • Blog Archive
  • Tutorials
  • About Us
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Guest Posts
  • SEO Analyzer
Free Dev Tools
  • JSON Beautifier
  • HTML Beautifier
  • CSS Beautifier
  • JS Beautifier
  • Password Generator
  • QR Code Generator
  • Hash Generator
  • Diff Checker
  • Base64 Encode/Decode
  • Word Counter
  • SEO Analyzer
By Language
  • Angular
  • C
  • C#
  • HTML/CSS
  • Java
  • JavaScript
  • Node.js
  • Python
  • React
  • Security
  • SQL Server
  • TypeScript
© 2026 Code2Night. All Rights Reserved.
Made with for developers  |  Privacy  ยท  Terms
Translate Page
We use cookies to improve your experience and analyze site traffic. By clicking Accept, you consent to our use of cookies. Privacy Policy
Accessibility
Text size
High contrast
Grayscale
Dyslexia font
Highlight links
Pause animations
Large cursor