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:
RoosterDragon
2014-07-18 20:58:50 +01:00
parent 58abd45ed9
commit c672ac5bad

View File

@@ -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)