You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

78 lines
2.3 KiB

using System;
using System.Collections.Generic;
using System.Linq;
using Znyc.Cloudcar.Admin.Commons.Data;
namespace Znyc.Cloudcar.Admin.Commons.Extensions
{
/// <summary>
/// 集合扩展方法
/// </summary>
public static class CollectionExtensions
{
/// <summary>
/// 如果条件成立,添加项
/// </summary>
public static void AddIf<T>(this ICollection<T> collection, T value, bool flag)
{
Check.NotNull(collection, nameof(collection));
if (flag)
{
collection.Add(value);
}
}
/// <summary>
/// 如果条件成立,添加项
/// </summary>
public static void AddIf<T>(this ICollection<T> collection, T value, Func<bool> func)
{
Check.NotNull(collection, nameof(collection));
if (func())
{
collection.Add(value);
}
}
/// <summary>
/// 如果不存在,添加项
/// </summary>
public static void AddIfNotExist<T>(this ICollection<T> collection, T value, Func<T, bool> existFunc = null)
{
Check.NotNull(collection, nameof(collection));
bool exists = existFunc == null ? collection.Contains(value) : existFunc(value);
if (!exists)
{
collection.Add(value);
}
}
/// <summary>
/// 如果不为空,添加项
/// </summary>
public static void AddIfNotNull<T>(this ICollection<T> collection, T value) where T : class
{
Check.NotNull(collection, nameof(collection));
if (value != null)
{
collection.Add(value);
}
}
/// <summary>
/// 获取对象,不存在对使用委托添加对象
/// </summary>
public static T GetOrAdd<T>(this ICollection<T> collection, Func<T, bool> selector, Func<T> factory)
{
Check.NotNull(collection, nameof(collection));
T item = collection.FirstOrDefault(selector);
if (item == null)
{
item = factory();
collection.Add(item);
}
return item;
}
}
}