Class ICollectionExtensions
- Namespace
- Wolfgang.Extensions.ICollection
- Assembly
- Wolfgang.Extensions.ICollection.dll
A collection of extension methods to ICollection<T>.
public static class ICollectionExtensions
- Inheritance
-
ICollectionExtensions
- Inherited Members
Methods
AddIfNotContains<T>(ICollection<T>, IEnumerable<T>)
Adds each item from items to
source if it is not already present.
public static int AddIfNotContains<T>(this ICollection<T> source, IEnumerable<T> items)
Parameters
sourceICollection<T>The collection to add to.
itemsIEnumerable<T>The candidate items.
Returns
- int
The number of items actually added (items already present in
source, or repeated withinitemsafter the first addition, are skipped).
Type Parameters
TThe type of items in the collection.
Exceptions
- ArgumentNullException
Thrown if
sourceoritemsis null.- NotSupportedException
Thrown if
sourceis read-only.
AddIfNotContains<T>(ICollection<T>, T)
Adds item to source if it is
not already present (per
Contains(T)).
public static bool AddIfNotContains<T>(this ICollection<T> source, T item)
Parameters
sourceICollection<T>The collection to add to.
itemTThe candidate item.
Returns
- bool
trueif the item was added;falseif it was already present.
Type Parameters
TThe type of items in the collection.
Remarks
Containment is determined by the target collection's own
Contains(T) implementation, which usually
uses Default. When
source is an ISet<T> the call is
delegated to Add(T), which returns the same
Boolean signal in a single lookup (and preserves the set's native
equality semantics, e.g. a custom IEqualityComparer<T>).
For other ICollection<T> implementations the
extension generalises the behaviour using
Contains(T) + Add(T).
Exceptions
- ArgumentNullException
Thrown if
sourceis null.- NotSupportedException
Thrown if
sourceis read-only.
AddRangeIf<T>(ICollection<T>, IEnumerable<T>, Func<T, bool>)
Adds every item from items to
source for which predicate
returns true.
public static void AddRangeIf<T>(this ICollection<T> source, IEnumerable<T> items, Func<T, bool> predicate)
Parameters
sourceICollection<T>The collection to add to.
itemsIEnumerable<T>The candidate items.
predicateFunc<T, bool>A function returning
truefor items that should be added.
Type Parameters
TThe type of items in the collection.
Remarks
Self-aliasing (passing the same instance for both
source and items) is safe:
items is snapshotted before mutation, so the
predicate sees a stable view and the matching items are appended
to the collection without tripping the mutate-during-enumerate
contract.
Exceptions
- ArgumentNullException
Thrown if
source,items, orpredicateis null.- NotSupportedException
Thrown if
sourceis read-only.
AddRange<T>(ICollection<T>, IEnumerable<T>)
Add all the specified items to the source collection.
public static void AddRange<T>(this ICollection<T> source, IEnumerable<T> items)
Parameters
sourceICollection<T>The source collection to add the items to.
itemsIEnumerable<T>The items to add to the source collection.
Type Parameters
TThe type of items in the collection.
Examples
// Add multiple strings to a list
ICollection<string> names = new List<string> { "Alice" };
names.AddRange(new[] { "Bob", "Charlie" });
// names now contains: "Alice", "Bob", "Charlie"
// Works with any ICollection<T> implementation
ICollection<int> numbers = new HashSet<int> { 1, 2 };
numbers.AddRange(new[] { 3, 4, 5 });
// numbers now contains: 1, 2, 3, 4, 5
// Add items from LINQ query results (requires using System.Linq)
var evenNumbers = Enumerable.Range(1, 10).Where(n => n % 2 == 0);
ICollection<int> myCollection = new List<int>();
myCollection.AddRange(evenNumbers);
// myCollection now contains: 2, 4, 6, 8, 10
Remarks
This extension method provides a convenient way to add multiple items to any collection that implements ICollection<T>, similar to the AddRange method available on List<T>.
The method iterates through each item in the items enumerable and
adds them one by one to the source collection using the Add method.
Edge Cases and Behavior:
- If
itemsis an empty enumerable, no items are added and the source collection remains unchanged. - If the source collection has constraints (e.g., unique items in HashSet), the Add method's behavior is preserved.
- If the source collection is read-only, the Add method will throw a NotSupportedException.
- The method does not check for duplicates; duplicate handling depends on the underlying collection implementation.
- When
sourceis a List<T> anditemsimplements ICollection<T>, the list's capacity is pre-allocated to avoid repeated resizing. - Self-aliasing (passing the same instance for both
sourceanditems) is safe:itemsis snapshotted before mutation, so the call effectively appends a copy of the current contents to the collection. - This method is not thread-safe. If multiple threads access the collection concurrently, external synchronization is required.
Exceptions
- ArgumentNullException
Thrown if source or items is null.
- NotSupportedException
Thrown if the collection is read-only.
IsEmpty<T>(ICollection<T>)
Determines whether the collection contains no elements.
public static bool IsEmpty<T>(this ICollection<T> source)
Parameters
sourceICollection<T>The collection to check.
Returns
- bool
trueif the collection contains no elements; otherwise,false.
Type Parameters
TThe type of items in the collection.
Examples
// Check if a list is empty
ICollection<string> names = new List<string>();
bool empty = names.IsEmpty(); // true
names.Add("Alice");
empty = names.IsEmpty(); // false
// Use in conditional logic
ICollection<int> results = GetResults();
if (results.IsEmpty())
{
Console.WriteLine("No results found.");
}
// Works with any ICollection<T> implementation
ICollection<string> set = new HashSet<string>(StringComparer.Ordinal);
bool isEmpty = set.IsEmpty(); // true
Remarks
This extension method provides a cleaner, more readable alternative to checking
source.Count == 0. It works with any ICollection<T> implementation.
This method checks the Count property directly, providing
a clear, self-documenting emptiness check. Typically O(1) for standard
ICollection<T> implementations; the Count
contract does not formally guarantee constant time, so a custom implementation could
be slower.
Edge Cases and Behavior:
- Returns
truefor a newly created, empty collection. - Returns
falseif the collection has one or more elements. - This method is not thread-safe. If multiple threads modify the collection concurrently, external synchronization is required.
Exceptions
- ArgumentNullException
Thrown if
sourceis null.
IsNotEmpty<T>(ICollection<T>)
Determines whether the collection contains one or more elements.
public static bool IsNotEmpty<T>(this ICollection<T> source)
Parameters
sourceICollection<T>The collection to check.
Returns
- bool
trueif the collection contains one or more elements; otherwise,false.
Type Parameters
TThe type of items in the collection.
Examples
// Check if a list has items
ICollection<string> names = new List<string> { "Alice" };
bool hasItems = names.IsNotEmpty(); // true
// Use in conditional logic
ICollection<int> results = GetResults();
if (results.IsNotEmpty())
{
ProcessResults(results);
}
// Works with any ICollection<T> implementation
ICollection<int> queue = new LinkedList<int>();
bool notEmpty = queue.IsNotEmpty(); // false
queue.Add(42);
notEmpty = queue.IsNotEmpty(); // true
Remarks
This extension method provides a cleaner, more readable alternative to checking
source.Count > 0. It works with any ICollection<T> implementation.
This method checks the Count property directly, providing
a clear, self-documenting non-emptiness check. Typically O(1) for standard
ICollection<T> implementations; the Count
contract does not formally guarantee constant time, so a custom implementation could
be slower.
Edge Cases and Behavior:
- Returns
falsefor a newly created, empty collection. - Returns
trueif the collection has one or more elements. - This method is not thread-safe. If multiple threads modify the collection concurrently, external synchronization is required.
Exceptions
- ArgumentNullException
Thrown if
sourceis null.
RemoveRange<T>(ICollection<T>, IEnumerable<T>)
Removes one occurrence of each item in items
from source.
public static void RemoveRange<T>(this ICollection<T> source, IEnumerable<T> items)
Parameters
sourceICollection<T>The collection to remove items from.
itemsIEnumerable<T>The items to remove.
Type Parameters
TThe type of items in the collection.
Remarks
Each item in items is removed using
Remove(T); if the target collection allows
duplicates and the same value appears multiple times in
items, multiple occurrences are removed (one per
call). Items in items that are not present in
source are silently skipped. Self-aliasing
(passing the same instance for both source and
items) is safe: items is
snapshotted before mutation, so the call empties the collection
cleanly without tripping the mutate-during-enumerate contract.
Exceptions
- ArgumentNullException
Thrown if
sourceoritemsis null.- NotSupportedException
Thrown if
sourceis read-only.
RemoveWhere<T>(ICollection<T>, Func<T, bool>)
Removes every item from source for which
predicate returns true.
public static int RemoveWhere<T>(this ICollection<T> source, Func<T, bool> predicate)
Parameters
sourceICollection<T>The collection to remove from.
predicateFunc<T, bool>A function returning
truefor items that should be removed.
Returns
- int
The number of items removed.
Type Parameters
TThe type of items in the collection.
Remarks
Matching items are materialised into a temporary list before
removal so the underlying collection can be mutated safely without
invalidating the enumerator. When source is a
HashSet<T> the call delegates to the native
RemoveWhere(Predicate<T>), which
skips the temporary-list allocation.
Exceptions
- ArgumentNullException
Thrown if
sourceorpredicateis null.- NotSupportedException
Thrown if
sourceis read-only.
ReplaceAll<T>(ICollection<T>, IEnumerable<T>)
Clears source and then adds every item from
items.
public static void ReplaceAll<T>(this ICollection<T> source, IEnumerable<T> items)
Parameters
sourceICollection<T>The collection to replace the contents of.
itemsIEnumerable<T>The new contents.
Type Parameters
TThe type of items in the collection.
Remarks
The operation is not atomic. If enumeration of
items throws midway through, the collection is
left empty (or with whatever items were already appended). Callers
that need atomic replacement should materialise the new contents
first. Self-aliasing (passing the same instance for both
source and items) is safe:
items is snapshotted before the Clear, so
the call is effectively a no-op rather than silently wiping the
collection.
Exceptions
- ArgumentNullException
Thrown if
sourceoritemsis null.- NotSupportedException
Thrown if
sourceis read-only.