using System; using System.Collections.Generic; using System.Linq; namespace Wabbajack { public static class EnumerableExt { #region Shuffle /// https://stackoverflow.com/questions/5807128/an-extension-method-on-ienumerable-needed-for-shuffling public static IEnumerable Shuffle(this IEnumerable source, Random rng) { return source.ShuffleIterator(rng); } private static IEnumerable ShuffleIterator( this IEnumerable source, Random rng) { var buffer = source.ToList(); for (int i = 0; i < buffer.Count; i++) { int j = rng.Next(i, buffer.Count); yield return buffer[j]; buffer[j] = buffer[i]; } } #endregion public static IEnumerable Cons(this IEnumerable coll, T next) { yield return next; foreach (var itm in coll) yield return itm; } /// /// Converts and filters a nullable enumerable to a non-nullable enumerable /// public static IEnumerable NotNull(this IEnumerable e) where T : class { // Filter out nulls return e.Where(e => e != null) // Cast to non nullable type .Select(e => e!); } /// /// Selects items that are castable to the desired type /// /// Type of the original enumerable to cast from /// Type to attempt casting to /// Enumerable to process /// Enumerable with only objects that were castable public static IEnumerable WhereCastable(this IEnumerable e) where T : class where R : T { return e.Where(e => e is R) .Select(e => (R)e); } } }