Returns true if there are no more than a set number of items in the IEnumerable
using System.Linq;
using System.Diagnostics;
namespace System.Collections.Generic
{
public static class EnumeratorExtensions
{
/// <summary>
/// Returns true if there are no more than a set number of items in the IEnumerable<T>.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source">The source list of items.</param>
/// <param name="number">The number of items that must exist.</param>
/// <returns>True if there are no more than the number of items, false otherwise.</returns>
public static bool AtMost<T>(this IEnumerable<T> source, int number)
{
if (source == null)
throw new ArgumentNullException("source");
bool result;
int count = 0;
using (IEnumerator<T> data = source.GetEnumerator())
{
while (count < number && data.MoveNext())
{
count++;
}
result = !data.MoveNext();
}
return result;
}
/// <summary>
/// Returns true if there are no more than a set number of items in the IEnumerable<T> that satisfy a given condition.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source">The source list of items.</param>
/// <param name="number">The number of items that must exist.</param>
/// <param name="predicate">The condition to apply to the items.</param>
/// <returns>True if there are no more than the number of items, false otherwise.</returns>
public static bool AtMost<T>(this IEnumerable<T> source, int number, Func<T, bool> condition)
{
if (source == null)
throw new ArgumentNullException("source");
if (condition == null)
throw new ArgumentNullException("condition");
bool result;
int count = 0;
using (IEnumerator<T> data = source.GetEnumerator())
{
while (count < number && data.MoveNext())
{
if (condition(data.Current))
count++;
}
result = !data.MoveNext();
}
return result;
}
}
}
Related examples in the same category