ソースコード
System.Random 版
using System;
using System.Collections.Generic;
using System.Linq;
public static partial class IEnumerableExt
{
private static readonly Random m_random = new Random();
public static T RandomAt<T>( this IEnumerable<T> self )
{
return self.Any()
? self.ElementAt( m_random.Next( self.Count() ) )
: default;
}
}
UnityEngine.Random 版
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public static partial class IEnumerableExt
{
public static T RandomAt<T>( this IEnumerable<T> self )
{
return self.Any()
? self.ElementAt( Random.Range( 0, self.Count() ) )
: default;
}
}
使い方
var list = new[] { 1, 2, 3, 4, 5 };
var value = list.RandomAt();