namespace GFramework.Core.extensions;
///
/// 集合扩展方法
///
public static class CollectionExtensions
{
///
/// 对集合中的每个元素执行指定操作
///
/// 集合元素类型
/// 源集合
/// 要对每个元素执行的操作
/// 当 source 或 action 为 null 时抛出
///
///
/// var numbers = new[] { 1, 2, 3 };
/// numbers.ForEach(n => Console.WriteLine(n));
///
///
public static void ForEach(this IEnumerable source, Action action)
{
ArgumentNullException.ThrowIfNull(source);
ArgumentNullException.ThrowIfNull(action);
foreach (var item in source) action(item);
}
///
/// 检查集合是否为 null 或空
///
/// 集合元素类型
/// 要检查的集合
/// 如果集合为 null 或不包含任何元素,则返回 true;否则返回 false
///
///
/// List<int>? numbers = null;
/// if (numbers.IsNullOrEmpty()) { /* ... */ }
///
///
public static bool IsNullOrEmpty(this IEnumerable? source)
{
return source is null || !source.Any();
}
///
/// 过滤掉集合中的 null 元素
///
/// 集合元素类型(引用类型)
/// 源集合
/// 不包含 null 元素的集合
/// 当 source 为 null 时抛出
///
///
/// var items = new string?[] { "a", null, "b", null, "c" };
/// var nonNull = items.WhereNotNull(); // ["a", "b", "c"]
///
///
public static IEnumerable WhereNotNull(this IEnumerable source) where T : class
{
ArgumentNullException.ThrowIfNull(source);
return source.Where(item => item is not null)!;
}
///
/// 将集合转换为字典,如果存在重复键则使用最后一个值
///
/// 源集合元素类型
/// 字典键类型
/// 字典值类型
/// 源集合
/// 键选择器函数
/// 值选择器函数
/// 转换后的字典
/// 当 source、keySelector 或 valueSelector 为 null 时抛出
///
///
/// var items = new[] { ("a", 1), ("b", 2), ("a", 3) };
/// var dict = items.ToDictionarySafe(x => x.Item1, x => x.Item2);
/// // dict["a"] == 3 (最后一个值)
///
///
public static Dictionary ToDictionarySafe(
this IEnumerable source,
Func keySelector,
Func valueSelector) where TKey : notnull
{
ArgumentNullException.ThrowIfNull(source);
ArgumentNullException.ThrowIfNull(keySelector);
ArgumentNullException.ThrowIfNull(valueSelector);
var dictionary = new Dictionary();
foreach (var item in source)
{
var key = keySelector(item);
var value = valueSelector(item);
dictionary[key] = value; // 覆盖重复键
}
return dictionary;
}
}