using System;
using System.Collections;
using System.Collections.Generic;
namespace Chernobyl.Collections.Generic
{
///
/// A set of extension methods for the type.
///
public static class CollectionExtensions
{
///
/// Adds several items to an . Note that
/// this implementation performs a foreach over the items to be added
/// and adds each one using . This
/// will be slow over some types but
/// necessary in cases where it is the only option.
///
/// The type of the items contained within the
/// .
/// The that is to
/// have the items added to it.
/// The items that are to be added to the collection.
public static void AddRange(this ICollection collection, IEnumerable items)
{
foreach (T value in items)
collection.Add(value);
}
///
/// Adds several items to an . Note that
/// this implementation performs a foreach over the items to be added
/// and adds each one using . This
/// will be slow over some types but
/// necessary in cases where it is the only option.
///
/// The type of the items contained within the
/// .
/// The that is to
/// have the items added to it.
/// The items that are to be added to the collection.
public static void AddRange(this ICollection collection, params T[] items) =>
collection.AddRange((IEnumerable)items);
///
/// Removes several items from an .
///
/// The type of the items contained within the
/// .
/// The that is to
/// have the items removed from it.
/// The items that are to be removed from the
/// .
/// Thrown if
/// and are the same instance. This method should
/// not be used to remove all items from an
/// as would be a faster way to
/// do that.
public static void RemoveRange(this ICollection collection, IEnumerable items)
{
if(ReferenceEquals(collection, items))
throw new ArgumentException("The IEnumerable of items being " +
"removed (parameter named 'items') and " +
"the ICollection that the items " +
"are being removed from are the same " +
"instance. Use ICollection.Clear() " +
"if you want to remove all items from " +
"an ICollection", nameof(items));
foreach (T value in items)
collection.Remove(value);
}
///
/// Returns true if the is within the range of ,
/// false if otherwise.
///
public static bool IsInBounds(this ICollection values, int index)
=> 0 <= index && index <= (values.Count - 1);
///
/// Returns true if the is within the range of ,
/// false if otherwise.
///
public static bool IsInBounds(this ICollection values, int index)
=> 0 <= index && index <= (values.Count - 1);
///
/// Returns true if the is within the range of ,
/// false if otherwise.
///
public static bool IsInBounds(this T[] values, int index)
// This method exists to prevent ambiguous reference compiler error that results from
// calling IsInBounds on arrays.
=> ((ICollection)values).IsInBounds(index);
}
}