56 lines
1.7 KiB
C#
56 lines
1.7 KiB
C#
namespace System.Collections.Generic
|
|
{
|
|
/// <summary>
|
|
/// Provides extension methods for generic <see cref="ICollection{T}"/> implementations.
|
|
/// </summary>
|
|
public static class CollectionExtensions
|
|
{
|
|
/// <summary>
|
|
/// Add the <paramref name="item"/> to the <paramref name="collection"/> if it is not <see langword="null"/>.
|
|
/// </summary>
|
|
/// <typeparam name="T">The type of the elements in the collection</typeparam>
|
|
/// <param name="collection">The collection.</param>
|
|
/// <param name="item">The item to add if not <see langword="null"/>.</param>
|
|
public static void AddIfNotNull<T>(this ICollection<T> collection, T item)
|
|
{
|
|
#if NET8_0_OR_GREATER
|
|
ArgumentNullException.ThrowIfNull(collection);
|
|
#else
|
|
if (collection == null)
|
|
throw new ArgumentNullException(nameof(collection));
|
|
#endif
|
|
|
|
if (item == null)
|
|
return;
|
|
|
|
collection.Add(item);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Adds a <see cref="AddRange{T}(ICollection{T}, IEnumerable{T})"/> functionallity to <see cref="ICollection{T}"/>.
|
|
/// </summary>
|
|
/// <typeparam name="T">The type of the elements in the collection.</typeparam>
|
|
/// <param name="collection">The collection.</param>
|
|
/// <param name="items">The items to add.</param>
|
|
public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> items)
|
|
{
|
|
#if NET8_0_OR_GREATER
|
|
ArgumentNullException.ThrowIfNull(collection);
|
|
ArgumentNullException.ThrowIfNull(items);
|
|
#else
|
|
if (collection == null)
|
|
throw new ArgumentNullException(nameof(collection));
|
|
|
|
if (items == null)
|
|
throw new ArgumentNullException(nameof(items));
|
|
#endif
|
|
|
|
if (collection == items)
|
|
return;
|
|
|
|
foreach (var item in items)
|
|
collection.Add(item);
|
|
}
|
|
}
|
|
}
|