|
namespace DevWilson
{
using System;
using System.Collections.Generic;
/// <summary>
/// Adds extension methods for System.Collections.Generic.IList<T>.
/// </summary>
public static class IListRandomExtensions
{
private static Random random = new Random();
/// <summary>
/// Randomly shuffles the elements within the list.
/// </summary>
/// <typeparam name="T">The type of elements in the list.</typeparam>
/// <param name="list">Represents a collection of objects that can be individually accessed by index.</param>
public static void Shuffle<T>(this IList<T> list)
{
if (list.Count <= 1)
{
return; // nothing to do
}
// don't shuffle the last element with itself
for (int i = 0; i < list.Count - 1; i++)
{
T x = list[i];
int index = random.Next(i + 1, list.Count);
list[i] = list[index];
list[index] = x;
}
}
/// <summary>
/// Returns a single element from the list, selected at random.
/// </summary>
/// <typeparam name="T">The type of elements in the list.</typeparam>
/// <param name="list">Represents a collection of objects that can be individually accessed by index.</param>
/// <returns>An element from the list or the default value if no elements exist.</returns>
public static T GetRandom<T>(this IList<T> list)
{
if (list.Count == 0)
{
return default(T);
}
return list[random.Next(0, list.Count)];
}
}
}
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
Hi, my name's Andy Wilson and I live in Cambridge, UK where I work as a Senior C# Software Developer.