Example #1
0
        public static T Random <T>([NotNull] this IEnumerable <T> source)
        {
            // Buffer all elements
            var asReadOnlyList = source as IReadOnlyList <T> ?? source.ToArray();

            // If there are no elements - throw
            if (!asReadOnlyList.Any())
            {
                throw new InvalidOperationException("Sequence contains no elements.");
            }

            return(asReadOnlyList[RandomEx.GetInt(0, asReadOnlyList.Count)]);
        }