Added extension method: AbpCollectionExtensions.AddIfNotContains

pull/272/head
Halil İbrahim Kalkan 8 years ago
parent b031c3d63c
commit de874abb17

@ -20,7 +20,7 @@ namespace System.Collections.Generic
/// <summary>
/// Adds an item to the collection if it's not already in the collection.
/// </summary>
/// <param name="source">Collection</param>
/// <param name="source">The collection</param>
/// <param name="item">Item to check and add</param>
/// <typeparam name="T">Type of the items in the collection</typeparam>
/// <returns>Returns True if added, returns False if not.</returns>
@ -38,7 +38,30 @@ namespace System.Collections.Generic
}
/// <summary>
/// Removed all items from a collection those satisfy the given <paramref name="predicate"/>.
/// Adds an item to the collection if it's not already in the collection based on the given <paramref name="predicate"/>.
/// </summary>
/// <param name="source">The collection</param>
/// <param name="predicate">The condition to decide if the item is already in the collection</param>
/// <param name="itemFactory">A factory that returns the item</param>
/// <typeparam name="T">Type of the items in the collection</typeparam>
/// <returns>Returns True if added, returns False if not.</returns>
public static bool AddIfNotContains<T>([NotNull] this ICollection<T> source, [NotNull] Func<T, bool> predicate, [NotNull] Func<T> itemFactory)
{
Check.NotNull(source, nameof(source));
Check.NotNull(source, nameof(predicate));
Check.NotNull(itemFactory, nameof(itemFactory));
if (source.Any(predicate))
{
return false;
}
source.Add(itemFactory());
return true;
}
/// <summary>
/// Removed all items from the collection those satisfy the given <paramref name="predicate"/>.
/// </summary>
/// <typeparam name="T">Type of the items in the collection</typeparam>
/// <param name="source">The collection</param>

@ -0,0 +1,26 @@
using Shouldly;
using Xunit;
namespace System.Collections.Generic
{
public class AbpCollectionExtensions_Tests
{
[Fact]
public void AddIfNotContains_With_Predicate()
{
var collection = new List<int> {4, 5, 6};
collection.AddIfNotContains(x => x == 5, () => 5);
collection.Count.ShouldBe(3);
collection.AddIfNotContains(x => x == 42, () => 42);
collection.Count.ShouldBe(4);
collection.AddIfNotContains(x => x < 8, () => 8);
collection.Count.ShouldBe(4);
collection.AddIfNotContains(x => x > 999, () => 8);
collection.Count.ShouldBe(5);
}
}
}
Loading…
Cancel
Save