Skip to content

ICollection Extensions

Andrzej Kebab edited this page Jan 21, 2024 · 2 revisions

UtilityLibrary.Core

UtilityLibrary.Core provides extension methods for ICollection<T>.

Null / Empty

IsNullOrEmpty

Checks if the collection is either null or empty.

using UtilityLibrary.Core;
using System;
using System.Collections.Generic;

ICollection<int> numbers = null;
bool result = numbers.IsNullOrEmpty(); // Result: true

ICollection<string> names = new List<string>();
result = names.IsNullOrEmpty(); // Result: true

IsEmpty

Checks if the collection is empty. Throws a NullReferenceException if the collection is null.

using UtilityLibrary.Core;
using System;
using System.Collections.Generic;

ICollection<int> numbers = new List<int>();
bool result = numbers.IsEmpty(); // Result: true

ICollection<string> names = null;
// Throws NullReferenceException
result = names.IsEmpty();

Add Unique

AddUnique

Adds a unique item to the collection. If the item already exists, it will not be added. Returns true if the item already exists in the collection.

using UtilityLibrary.Core;
using System;
using System.Collections.Generic;

ICollection<int> numbers = new List<int> { 1, 2, 3 };
bool exists = numbers.AddUnique(3); // Result: true (3 already exists, not added)

AddRangeUnique

Adds a range of unique items to the collection. If an item already exists, it will not be added. Returns the number of items that already existed in the collection.

using UtilityLibrary.Core;
using System;
using System.Collections.Generic;

ICollection<int> numbers = new List<int> { 1, 2, 3 };
IEnumerable<int> newNumbers = new List<int> { 3, 4, 5 };
int count = numbers.AddRangeUnique(newNumbers); // Result: 2 (4 and 5 are added)

Clone this wiki locally