Return a random element in the provided IEnumerable. - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:IEnumerable

Description

Return a random element in the provided IEnumerable.

Demo Code


using System.Linq;
using System;//w  w  w .  j a  v a  2  s.c  o  m
using System.Collections.Generic;
using System.Collections;
using UnityEngine;

public class Main{
        /// <summary>
        /// Return a random element in the provided IEnumerable. 
        /// </summary>
        public static T GetRandomElement<T>(this IEnumerable<T> self)
        {
            if (self == null)
            {
                return default(T);
            }

            var count = self.Count();

            if (count == 0)
            {
                return default(T);
            }
            if (count == 1)
            {
                return self.ElementAt(0);
            }

            return self.ElementAt(UnityEngine.Random.Range(0, count));
        }
        /// <summary>
        /// Return a random element in the provided hashset. 
        /// </summary>
        public static T GetRandomElement<T>(this HashSet<T> self)
        {
            if (self == null)
            {
                Debug.LogException(new ArgumentNullException("self"));
                return default(T);
            }

            if (self.Count == 0)
                return default(T);
            if (self.Count == 1)
                return self.ElementAt(0);

            var randomIndex = UnityEngine.Random.Range(0, self.Count);

            return self.ElementAt(randomIndex);
        }
        /// <summary>
        /// Return a random element in the list. 
        /// </summary>
        public static T GetRandomElement<T>(this List<T> self)
        {
            if (self == null)
            {
                Debug.LogException(new ArgumentNullException("self"));
                return default(T);
            }

            if (self.Count == 0)
                return default(T);
            if (self.Count == 1)
                return self[0];

            return self[UnityEngine.Random.Range(0, self.Count)];
        }
}

Related Tutorials