Last active
August 29, 2015 14:04
-
-
Save TarasOsiris/c87523e46b6f0306b107 to your computer and use it in GitHub Desktop.
Collection extension methods
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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