Naveed’s Blog 2015 in review

The WordPress.com stats helper monkeys prepared a 2015 annual report for this blog.

Here’s an excerpt:

The concert hall at the Sydney Opera House holds 2,700 people. This blog was viewed about 22,000 times in 2015. If it were a concert at Sydney Opera House, it would take about 8 sold-out performances for that many people to see it.

Click here to see the complete report.

Advertisements

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
            PrintEmployees(employees);
            //randomize using extension
            var randomEmployees = Employee.GetAllEmployee().Randomize();
            //print them again
            Console.WriteLine("**************");
            PrintEmployees(randomEmployees);

Job Done!

Sample code is available on GitHub

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