C# – Random ordering of IEnumerable using Extensions

This is just a quick post about random ordering of IEnumerable types using C# extension. For example you have a IEnumerable of type ‘Employee’ object and you want to randomly pick 7 employee objects, how would you do that? This blog post will create a simple extension method for IEnumerable and show how to use it.

Step 1 : Create an extension class for IEnumerable as below :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Sample
    public static class EnumerableExtentions
       public static IEnumerable<T> Randomize<T>(this IEnumerable<T> source)
            var range= new Random();
            return source.Randomize(range);

        private static IEnumerable<T> Randomize<T>(this IEnumerable<T> source, Random range)
            if (source == null) throw new ArgumentNullException("source");
            if (range== null) throw new ArgumentNullException("range");

            return source.RandomizeAlgorithm(range);

        private static IEnumerable<T> RandomizeAlgorithm<T>(this IEnumerable<T> source, Random range)
            var temp = source.ToList();

            for (int i = 0; i < temp.Count; i++)
                int j = range.Next(i, temp.Count);
                yield return temp[j];

                temp[j] = temp[i];

Step 2 : Use it within your main code as below :

           //get all employees
            var employees = Employee.GetAllEmployee();
            //print in sequence
            //randomize using extension
            var randomEmployees = Employee.GetAllEmployee().Randomize();
            //print them again

Job Done!

Sample code is available on GitHub

Note : I am using Fisher–Yates shuffle  algorithm for randomizing the collection.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.