using NCC.Dependency; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NCC.Common.Collections { /// /// 集合扩展方法 /// [SuppressSniffer] public static class CollectionExtensions { /// /// 如果条件成立,添加项 /// public static void AddIf(this ICollection collection, T value, bool flag) { if (flag) { collection.Add(value); } } /// /// 如果条件成立,添加项 /// public static void AddIf(this ICollection collection, T value, Func func) { if (func()) { collection.Add(value); } } /// /// 如果不存在,添加项 /// public static void AddIfNotExist(this ICollection collection, T value, Func existFunc = null) { bool exists = existFunc == null ? collection.Contains(value) : collection.Any(existFunc); if (!exists) { collection.Add(value); } } /// /// 如果不为空,添加项 /// public static void AddIfNotNull(this ICollection collection, T value) where T : class { if (value != null) { collection.Add(value); } } /// /// 获取对象,不存在对使用委托添加对象 /// public static T GetOrAdd(this ICollection collection, Func selector, Func factory) { T item = collection.FirstOrDefault(selector); if (item == null) { item = factory(); collection.Add(item); } return item; } /// /// 判断集合是否为null或空集合 /// public static bool IsNullOrEmpty(this ICollection collection) { return collection == null || collection.Count == 0; } /// /// 交换两项的位置 /// public static void Swap(this List list, int index1, int index2) { if (index1 == index2) { return; } T tmp = list[index1]; list[index1] = list[index2]; list[index2] = tmp; } } }