Random Element from IEnumerable - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:IEnumerable

Description

Random Element from IEnumerable

Demo Code


using System.Linq;
using System.Collections.Generic;
using System.Collections;
using System;/*from w  ww.ja  v a2  s  .c  om*/

public class Main{
        public static T Random<T>(this IEnumerable<T> target)
    {
        int targetLength = target.Count();

        int randomIndex = UnityEngine.Random.Range(0, targetLength);

        return target.ElementAtOrDefault(targetLength==0 ? 0 : randomIndex);
    }
}

Related Tutorials