using System;
using System.Collections.Generic;
using System.Linq;
namespace Game
{
///
/// Provides additional methods for the
/// interface.
///
public static class EnumerableExtensions
{
///
/// Cycles through the integer values in the range [0, count).
///
///
/// The first value to return.
///
///
/// The number of values to return.
///
public static IEnumerable Cycle(int start, int count)
{
if (count < 1)
throw new ArgumentException("count must be at least 1");
if (start < 0 || start >= count)
throw new ArgumentException("start must be in the range [0, count)");
for (var i = start; i < count; ++i)
yield return i;
for (var i = 0; i < start; ++i)
yield return i;
}
///
/// Finds the index of the first item in the given sequence that
/// satisfies the given predicate.
///
///
/// The type of elements in the sequence.
///
///
/// The source sequence.
///
///
/// The predicate function.
///
///
/// The index of the first element in the source sequence for which
/// predicate(element) is true. If there is no such element, return
/// is null.
///
public static int? FindFirstIndex(this IEnumerable source, Func predicate) =>
source.Select((element, index) => predicate(element) ? index : default(int?))
.FirstOrDefault(index => index.HasValue);
///
/// Returns the first item in the given sequence that matches the
/// given predicate.
///
///
/// The type of elements in the sequence.
///
///
/// The source sequence.
///
///
/// The predicate to check against each element.
///
///
/// The value to return if no elements match the predicate.
///
///
/// The first item in the source sequence that matches the given
/// predicate, or the provided default value if none do.
///
public static T FirstOrDefault(this IEnumerable source, Func predicate, T defaultValue)
{
foreach (var element in source)
if (predicate(element))
return element;
return defaultValue;
}
}
}