using System.Collections.Generic; using System; using System.Linq; namespace Barotrauma.Extensions { public static class IEnumerableExtensions { public static HashSet ToHashSet(this IEnumerable source) { return new HashSet(source); } /// /// Randomizes the collection. /// public static IOrderedEnumerable Randomize(this IEnumerable source) { return source.OrderBy(i => Rand.Range(0f, 1f)); } public static T GetRandom(this IEnumerable source, Func predicate, Rand.RandSync randSync = Rand.RandSync.Unsynced) { return source.Where(predicate).GetRandom(randSync); } public static T GetRandom(this IEnumerable source, Rand.RandSync randSync = Rand.RandSync.Unsynced) { int count = source.Count(); return count == 0 ? default(T) : source.ElementAt(Rand.Range(0, count, randSync)); } /// /// Executes an action that modifies the collection on each element (such as removing items from the list). /// Creates a temporary list. /// public static void ForEachMod(this IEnumerable source, Action action) { var temp = new List(source); temp.ForEach(action); } /// /// Generic version of List.ForEach. /// Performs the specified action on each element of the collection (short hand for a foreach loop). /// public static void ForEach(this IEnumerable source, Action action) { foreach (var item in source) { action(item); } } /// /// Shorthand for !source.Any(predicate) -> i.e. not any. /// public static bool None(this IEnumerable source, Func predicate = null) { if (predicate == null) { return !source.Any(); } else { return !source.Any(predicate); } } public static bool Multiple(this IEnumerable source, Func predicate = null) { if (predicate == null) { return source.Count() > 1; } else { return source.Count(predicate) > 1; } } // source: https://stackoverflow.com/questions/19237868/get-all-children-to-one-list-recursive-c-sharp public static IEnumerable SelectManyRecursive(this IEnumerable source, Func> selector) { var result = source.SelectMany(selector); if (!result.Any()) { return result; } return result.Concat(result.SelectManyRecursive(selector)); } public static void AddIfNotNull(this IList source, T value) { if (value != null) { source.Add(value); } } } }