Improve Exts.Random by testing if the input sequence is a collection, thus avoiding the need to create a copy to get the count.
Using the ElementAt method also means that if the sequence is a list too, then the selection can be done via the indexer rather the enumerating the elements.
This commit is contained in:
@@ -108,8 +108,11 @@ namespace OpenRA
|
||||
|
||||
public static T Random<T>(this IEnumerable<T> ts, MersenneTwister r)
|
||||
{
|
||||
var xs = ts.ToArray();
|
||||
return xs[r.Next(xs.Length)];
|
||||
var xs = ts as ICollection<T>;
|
||||
if (xs != null)
|
||||
return xs.ElementAt(r.Next(xs.Count));
|
||||
var ys = ts.ToList();
|
||||
return ys[r.Next(ys.Count)];
|
||||
}
|
||||
|
||||
public static T RandomOrDefault<T>(this IEnumerable<T> ts, MersenneTwister r)
|
||||
|
||||
Reference in New Issue
Block a user