using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using JetBrains.Annotations;
namespace JiShe.CollectBus.Common.Extensions
{
///
/// Extension methods for Collections.
///
public static class CollectionExtensions
{
///
/// Adds an item to the collection if it's not already in the collection.
///
/// Collection
/// Item to check and add
/// Type of the items in the collection
/// Returns True if added, returns False if not.
[Description("项不在集合中则将其添加到集合中")]
public static bool AddIfNotContains([NotNull] this ICollection source, T item)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
if (source.Contains(item))
{
return false;
}
source.Add(item);
return true;
}
///
/// Adds items to the collection which are not already in the collection.
///
/// The collection
/// Item to check and add
/// Type of the items in the collection
/// Returns the added items.
public static IEnumerable AddIfNotContains([NotNull] this ICollection source, IEnumerable items)
{
var addedItems = new List();
foreach (var item in items)
{
if (source.Contains(item))
{
continue;
}
source.Add(item);
addedItems.Add(item);
}
return addedItems;
}
///
/// Adds an item to the collection if it's not already in the collection based on the given .
///
/// The collection
/// The condition to decide if the item is already in the collection
/// A factory that returns the item
/// Type of the items in the collection
/// Returns True if added, returns False if not.
public static bool AddIfNotContains([NotNull] this ICollection source, [NotNull] Func predicate, [NotNull] Func itemFactory)
{
if (source.Any(predicate))
{
return false;
}
source.Add(itemFactory());
return true;
}
///
/// Removes all items from the collection those satisfy the given .
///
/// Type of the items in the collection
/// The collection
/// The condition to remove the items
/// List of removed items
[Description("从集合中移除满足给定条件的所有项")]
public static IList RemoveAll([NotNull] this ICollection source, Func predicate)
{
var items = source.Where(predicate).ToList();
foreach (var item in items)
{
source.Remove(item);
}
return items;
}
///
/// Removes all items from the collection those satisfy the given .
///
/// Type of the items in the collection
/// The collection
/// Items to be removed from the list
public static void RemoveAll([NotNull] this ICollection source, IEnumerable items)
{
foreach (var item in items)
{
source.Remove(item);
}
}
}
}