【发布时间】:2011-10-27 13:20:27
【问题描述】:
我正在尝试使用 OrderedDictionary 作为以下扩展函数的参数(顺便说一下,如果您认为 collection.Reverse().Where(i => predicate(i)).Take(n) 会更好,请告诉我!),但我使用的通用 OrderedDictionary 实现(基于 @987654321 @) 没有实现 IList。
集合只需要通过基于整数的索引提供对其元素的访问(OrderedDictionary 就是这样做的)。
是否有另一种方法来指定此要求,而不会造成重载?
/// <summary>
/// Return n elements, starting from the end of collection, that satisfy predicate.
/// </summary>
/// <param name="collection"></param>
/// <param name="predicate"></param>
/// <param name="n">Max number of elements to return</param>
/// <returns></returns>
public static IEnumerable<T> LastBefore<T>(this IList<T> collection, Func<T, bool> predicate, int n) {
if (collection == null)
{
throw new ArgumentNullException("collection");
}
for (int i = collection.Count - 1; i >= 0; i--)
{
if (n == 0) break;
if (predicate(collection[i]))
{
--n;
yield return collection[i];
}
}
}
【问题讨论】:
标签: c# .net list data-structures interface