using System.Collections.Generic; using System.Linq; using UnityEngine; namespace Monpl.Utils.Extensions { public static class CollectionExtensions { #region List public static T GetFirst(this List list) { if (list.Count == 0) throw new System.IndexOutOfRangeException("List Length is 0"); return list[0]; } public static T GetLast(this List list) { if (list.Count == 0) throw new System.IndexOutOfRangeException("List Length is 0"); return list[list.Count - 1]; } public static T GetRandom(this List list) { if (list.Count == 0) throw new System.IndexOutOfRangeException("Cannot select a random item from an empty list"); return list[Random.Range(0, list.Count)]; } public static T GetRandomAndRemove(this List list) { if (list.Count == 0) throw new System.IndexOutOfRangeException("List Length is 0"); var randomIndex = Random.Range(0, list.Count); var ret = list[randomIndex]; list.RemoveAt(randomIndex); return ret; } public static void RemoveFirst(this List list) { list.RemoveAt(0); } public static void RemoveLast(this List list) { list.RemoveAt(list.Count - 1); } public static T GetFirstAndRemove(this List list) { var ret = list.GetFirst(); list.RemoveFirst(); return ret; } public static T GetLastAndRemove(this List list) { var ret = list.GetLast(); list.RemoveLast(); return ret; } public static void Shuffle(this IList list) { var rng = new System.Random(); var n = list.Count; while (n > 1) { n--; var k = rng.Next(n + 1); var value = list[k]; list[k] = list[n]; list[n] = value; } } public static void Swap(IList list, int indexA, int indexB) { T tmp = list[indexA]; list[indexA] = list[indexB]; list[indexB] = tmp; } #endregion #region Dictionary public static TKey GetRandomKey(this Dictionary dictionary) { var existKeyList = dictionary.Select(div => div.Key).ToList(); return existKeyList.GetRandom(); } public static TValue GetRandomValue(this Dictionary dictionary) { var existKeyList = new List(); foreach (var div in dictionary) existKeyList.Add(div.Value); return existKeyList.GetRandom(); } #endregion } }