Skip to content

Instantly share code, notes, and snippets.

@TarasOsiris
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TarasOsiris/c87523e46b6f0306b107 to your computer and use it in GitHub Desktop.
Save TarasOsiris/c87523e46b6f0306b107 to your computer and use it in GitHub Desktop.
Collection extension methods
using System.Collections.Generic;
using System;
namespace TarasOsirisGists
{
public static class ListUtils
{
private static Random _rnd;
/// <summary>
/// Gets the random element from specified list.
/// </summary>
/// <returns>The random element.</returns>
/// <param name="list">List to get element from.</param>
/// <typeparam name="T">The 1st type parameter.</typeparam>
public static T GetRandomElement<T>(this IList<T> list)
{
if (_rnd == null)
{
_rnd = new Random();
}
return list[_rnd.Next(list.Count)];
}
public static bool IsEmpty<T>(this IList<T> list)
{
return list.Count == 0;
}
public static bool IsLast<T>(this IList<T> list, T element)
{
return list.IndexOf(element) == list.Count - 1;
}
public static bool IsFirst<T>(this IList<T> list, T element)
{
return list.IndexOf(element) == 0;
}
public static void Shuffle<T>(this IList<T> list)
{
var rng = new Random();
int n = list.Count;
while (n > 1)
{
n--;
int k = rng.Next(n + 1);
T value = list[k];
list[k] = list[n];
list[n] = value;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment