EnumerableExtensions
EnumerableExtensions 扩展类文档
Section titled “EnumerableExtensions 扩展类文档”EnumerableExtensions 是一个静态扩展类,为 IEnumerable<T> 和 ICollection<T> 类型提供了丰富的扩展方法,包括空值判断、安全操作、集合操作、分页排序、统计计算、集合转换、批量操作等功能,旨在简化集合处理,提高代码的安全性和可读性,特别是用于处理可能为空的集合类型的日常操作场景。
主要功能模块
Section titled “主要功能模块”1. IEnumerable 扩展方法
Section titled “1. IEnumerable 扩展方法”提供对可枚举集合的各种安全操作方法。
状态判断方法
Section titled “状态判断方法”IsNullOrEmpty<T>()- 判断集合是否为 null 或空IsNotEmpty<T>()- 判断集合是否不为空SafeCount<T>()- 获取集合元素数量(安全)CountIf<T>(Func<T, bool> predicate)- 获取集合元素数量(使用条件过滤)
安全获取元素方法
Section titled “安全获取元素方法”FirstOrDefaultSafe<T>()- 获取集合的第一个元素,若为空则返回默认值FirstOrDefaultSafe<T>(Func<T, bool> predicate)- 获取集合的第一个满足条件的元素LastOrDefaultSafe<T>()- 获取集合的最后一个元素,若为空则返回默认值LastOrDefaultSafe<T>(Func<T, bool> predicate)- 获取集合的最后一个满足条件的元素ElementAtOrDefaultSafe<T>(int index)- 获取集合中指定索引的元素,若越界则返回默认值SingleOrDefaultSafe<T>()- 获取集合的单个元素,若为空或包含多个元素则返回默认值SingleOrDefaultSafe<T>(Func<T, bool> predicate)- 获取集合的单个满足条件的元素
集合操作方法
Section titled “集合操作方法”ContainsSafe<T>(T item)- 判断集合是否包含指定元素(支持 null 集合)ContainsWhere<T>(Func<T, bool> predicate)- 判断集合是否包含满足指定条件的元素ToListSafe<T>()- 将集合转换为 List(安全)ToArraySafe<T>()- 将集合转换为数组(安全)DistinctSafe<T>()- 集合去重(安全)DistinctBySafe<TSource, TKey>(Func<TSource, TKey> keySelector)- 根据指定键去重(安全)WhereSafe<T>(Func<T, bool> predicate)- 集合过滤(安全)SelectSafe<TSource, TResult>(Func<TSource, TResult> selector)- 集合投影(安全)GroupBySafe<TSource, TKey>(Func<TSource, TKey> keySelector)- 集合分组(安全)OrderBySafe<TSource, TKey>(Func<TSource, TKey> keySelector)- 集合排序(安全)OrderByDescendingSafe<TSource, TKey>(Func<TSource, TKey> keySelector)- 集合逆序排序(安全)ReverseSafe<T>()- 集合反转(安全)Shuffle<T>()- 集合随机排序(洗牌)
集合判断方法
Section titled “集合判断方法”AllSafe<T>(Func<T, bool> predicate)- 判断是否全部满足条件(安全)AnySafe<T>(Func<T, bool> predicate)- 判断是否存在满足条件的元素(安全)SequenceEqualSafe<T>(IEnumerable<T> second)- 判断两个集合是否相等(安全)ContainsSameElements<T>(IEnumerable<T> second)- 判断两个集合是否包含相同元素(忽略顺序)ContainsNull<T>()- 判断集合是否包含 null 元素
集合合并方法
Section titled “集合合并方法”ConcatSafe<T>(IEnumerable<T> second)- 合并两个集合(安全)ConcatMany<T>(params IEnumerable<T>[] sources)- 合并多个集合IntersectSafe<T>(IEnumerable<T> second)- 获取两个集合的交集(安全)UnionSafe<T>(IEnumerable<T> second)- 获取两个集合的并集(安全)ExceptSafe<T>(IEnumerable<T> second)- 获取两个集合的差集(安全)
Page<T>(int pageIndex, int pageSize)- 集合分页(安全)
SumSafe()- 集合求和(安全)- 支持 int、double、decimal、floatAverageSafe()- 集合平均值(安全)- 支持 int、double、decimal、floatMaxSafe()- 集合最大值(安全)- 支持 int、double、decimal、floatMinSafe()- 集合最小值(安全)- 支持 int、double、decimal、floatMaxBy<TSource, TKey>(Func<TSource, TKey> keySelector)- 获取集合中最大值对应的元素MinBy<TSource, TKey>(Func<TSource, TKey> keySelector)- 获取集合中最小值对应的元素
批量操作方法
Section titled “批量操作方法”ForEachSafe<T>(Action<T> action)- 集合遍历执行操作(安全)ForEachIndexed<T>(Action<T, int> action)- 集合遍历执行操作(带索引)ForEachAsync<T>(Func<T, Task> action)- 集合遍历执行异步操作ChunkSafe<T>(int size)- 集合分块(按指定大小分组)Batch<T>(int batchSize, Action<IEnumerable<T>> action)- 集合分批处理BatchAsync<T>(int batchSize, Func<IEnumerable<T>, Task> action)- 集合分批异步处理
集合转换方法
Section titled “集合转换方法”ToDictionarySafe<TSource, TKey, TValue>(Func<TSource, TKey> keySelector, Func<TSource, TValue> valueSelector)- 集合转换为字典(安全)ToHashSetSafe<T>()- 集合转换为 HashSet(安全)ToDataTable<T>()- 集合转换为 DataTable(自动推断列名和类型)ToConcurrentDictionary<TKey, TValue>()- 集合转换为 ConcurrentDictionary
RemoveNulls<T>()- 集合去除 null 元素JoinToString<T>(string separator)- 将集合元素连接为字符串JoinToString<T>(Func<T, string> selector, string separator)- 将集合元素连接为字符串(带选择器)
2. ICollection 扩展方法
Section titled “2. ICollection 扩展方法”提供对集合类型的安全操作方法。
状态判断方法
Section titled “状态判断方法”IsNullOrEmptySafe<T>()- 判断集合是否为 null 或空(IEnumerable)IsNullOrEmptySafe<T>()- 判断集合是否为 null 或空(ICollection)IsNotEmpty<T>()- 判断集合是否不为空
元素操作方法
Section titled “元素操作方法”AddSafe<T>(T item)- 安全添加元素到集合RemoveSafe<T>(T item)- 安全移除元素ClearSafe<T>()- 清空集合(安全)AddRangeSafe<T>(IEnumerable<T> items)- 批量添加元素(安全)RemoveRangeSafe<T>(IEnumerable<T> items)- 批量移除元素(安全)
方法详细说明
Section titled “方法详细说明”IsNullOrEmptySafe
Section titled “IsNullOrEmptySafe”判断集合是否为 null 或空。
public static bool IsNullOrEmptySafe<T>(this IEnumerable<T> source)public static bool IsNullOrEmptySafe<T>(this ICollection<T> collection)参数:
source: 待判断的集合
返回值:
- 如果集合为 null 或不包含任何元素,返回 true;否则返回 false
示例:
List<int> list1 = null;List<int> list2 = new List<int>();List<int> list3 = new List<int> { 1, 2, 3 };
bool result1 = list1.IsNullOrEmptySafe(); // truebool result2 = list2.IsNullOrEmptySafe(); // truebool result3 = list3.IsNullOrEmptySafe(); // falseIsNotEmpty
Section titled “IsNotEmpty”判断集合是否不为空。
public static bool IsNotEmpty<T>(this IEnumerable<T> source)返回值:
- 如果集合不为 null 且包含元素,返回 true;否则返回 false
示例:
List<int> list = new List<int> { 1, 2, 3 };bool result = list.IsNotEmpty(); // trueSafeCount
Section titled “SafeCount”获取集合元素数量(安全,支持 null 集合)。
public static int SafeCount<T>(this IEnumerable<T> source)CountIf
Section titled “CountIf”获取满足条件的元素数量。
public static int CountIf<T>(this IEnumerable<T> source, Func<T, bool> predicate)参数:
source: 集合predicate: 条件判断函数
返回值:
- 满足条件的元素数量
示例:
var list = new List<int> { 1, 2, 3, 4, 5 };var count = list.CountIf(x => x > 3); // 2参数:
source: 集合
返回值:
- 集合元素数量,如果集合为 null 则返回 0
示例:
List<int> list1 = null;List<int> list2 = new List<int> { 1, 2, 3 };
int count1 = list1.SafeCount(); // 0int count2 = list2.SafeCount(); // 3安全获取元素
Section titled “安全获取元素”FirstOrDefaultSafe
Section titled “FirstOrDefaultSafe”获取集合的第一个元素,若为空则返回默认值。
public static T FirstOrDefaultSafe<T>(this IEnumerable<T> source)public static T FirstOrDefaultSafe<T>(this IEnumerable<T> source, Func<T, bool> predicate)参数:
source: 集合predicate: 过滤条件(可选)
返回值:
- 第一个元素或默认值
示例:
List<int> list1 = null;List<int> list2 = new List<int> { 1, 2, 3, 4, 5 };
int result1 = list1.FirstOrDefaultSafe(); // 0 (default)int result2 = list2.FirstOrDefaultSafe(); // 1int result3 = list2.FirstOrDefaultSafe(x => x > 3); // 4ElementAtOrDefaultSafe
Section titled “ElementAtOrDefaultSafe”获取集合中指定索引的元素,若索引越界则返回默认值。
public static T ElementAtOrDefaultSafe<T>(this IEnumerable<T> source, int index)参数:
source: 集合index: 索引位置
返回值:
- 指定索引的元素或默认值
示例:
List<int> list = new List<int> { 1, 2, 3 };
int result1 = list.ElementAtOrDefaultSafe(1); // 2int result2 = list.ElementAtOrDefaultSafe(10); // 0 (default)LastOrDefaultSafe
Section titled “LastOrDefaultSafe”获取集合最后一个元素,若集合为空则返回默认值。
public static T LastOrDefaultSafe<T>(this IEnumerable<T> source)public static T LastOrDefaultSafe<T>(this IEnumerable<T> source, Func<T, bool> predicate)参数:
source: 集合predicate: 过滤条件(可选)
返回值:
- 最后一个元素或默认值
示例:
List<int> list = new List<int> { 1, 2, 3, 4, 5 };int result = list.LastOrDefaultSafe(); // 5int result2 = list.LastOrDefaultSafe(x => x < 3); // 2SingleOrDefaultSafe
Section titled “SingleOrDefaultSafe”获取集合唯一元素,若集合为空或包含多个元素则返回默认值。
public static T SingleOrDefaultSafe<T>(this IEnumerable<T> source)public static T SingleOrDefaultSafe<T>(this IEnumerable<T> source, Func<T, bool> predicate)参数:
source: 集合predicate: 过滤条件(可选)
返回值:
- 唯一元素或默认值
示例:
List<int> list = new List<int> { 5 };int result = list.SingleOrDefaultSafe(); // 5ContainsSafe
Section titled “ContainsSafe”判断集合是否包含指定元素(支持 null 集合)。
public static bool ContainsSafe<T>(this IEnumerable<T> source, T item)参数:
source: 集合item: 要查找的元素
返回值:
- 如果集合包含指定元素返回 true;否则返回 false
示例:
List<int> list1 = null;List<int> list2 = new List<int> { 1, 2, 3 };
bool result1 = list1.ContainsSafe(2); // falsebool result2 = list2.ContainsSafe(2); // trueDistinctBySafe
Section titled “DistinctBySafe”根据指定键去重(安全)。
public static IEnumerable<TSource> DistinctBySafe<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)参数:
source: 集合keySelector: 键选择器
返回值:
- 去重后的集合
示例:
var list = new List<Person>{ new Person { Id = 1, Name = "Alice" }, new Person { Id = 2, Name = "Bob" }, new Person { Id = 1, Name = "Alice2" }};
var distinct = list.DistinctBySafe(x => x.Id).ToList();// 结果:Id=1 (Alice), Id=2 (Bob)ContainsWhere
Section titled “ContainsWhere”判断集合是否包含满足指定条件的元素(支持 null 集合)。
public static bool ContainsWhere<T>(this IEnumerable<T> source, Func<T, bool> predicate)参数:
source: 集合predicate: 条件谓词
返回值:
- 如果集合包含满足条件的元素返回 true;否则返回 false
示例:
List<int> list = new List<int> { 1, 2, 3, 4, 5 };
bool result = list.ContainsWhere(x => x > 3); // trueToListSafe
Section titled “ToListSafe”安全地将集合转换为 List(支持 null 集合)。
public static List<T> ToListSafe<T>(this IEnumerable<T> source)返回值: List 实例,如果源为 null 则返回空 List
ToArraySafe
Section titled “ToArraySafe”安全地将集合转换为数组(支持 null 集合)。
public static T[] ToArraySafe<T>(this IEnumerable<T> source)返回值: 数组,如果源为 null 则返回空数组
ToHashSetSafe
Section titled “ToHashSetSafe”安全地将集合转换为 HashSet(支持 null 集合)。
public static HashSet<T> ToHashSetSafe<T>(this IEnumerable<T> source)返回值: HashSet 实例,如果源为 null 则返回空 HashSet
ToDictionarySafe
Section titled “ToDictionarySafe”安全地将集合转换为字典(支持 null 集合和选择器)。
public static Dictionary<TKey, TValue> ToDictionarySafe<TSource, TKey, TValue>( this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TValue> valueSelector)参数:
source: 源集合keySelector: 键选择器valueSelector: 值选择器
返回值: 字典实例,如果源为 null 或选择器为 null 则返回空字典
示例:
var users = new[] { new { Id = 1, Name = "Alice" }, new { Id = 2, Name = "Bob" } };var dict = users.ToDictionarySafe(u => u.Id, u => u.Name);// dict: { [1] = "Alice", [2] = "Bob" }ToDataTable
Section titled “ToDataTable”将集合转换为 DataTable(自动推断列名和类型)。
public static System.Data.DataTable ToDataTable<T>(this IEnumerable<T> source)参数:
source: 源集合
返回值: DataTable 实例,列名和类型根据 T 的属性自动推断
示例:
var users = new[] { new { Id = 1, Name = "Alice" }, new { Id = 2, Name = "Bob" } };var table = users.ToDataTable();// table 包含 Id (Int32) 和 Name (String) 两列ToConcurrentDictionary
Section titled “ToConcurrentDictionary”将集合转换为 ConcurrentDictionary(线程安全字典)。
public static ConcurrentDictionary<TKey, TValue> ToConcurrentDictionary<TKey, TValue>( this IEnumerable<KeyValuePair<TKey, TValue>> source)
public static ConcurrentDictionary<TKey, TValue> ToConcurrentDictionary<TSource, TKey, TValue>( this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TValue> valueSelector)参数:
source: 源集合keySelector: 键选择器(第二个重载)valueSelector: 值选择器(第二个重载)
返回值: ConcurrentDictionary 实例,如果源为 null 则返回空 ConcurrentDictionary
示例:
var pairs = new[] { KeyValuePair.Create("a", 1), KeyValuePair.Create("b", 2) };var dict = pairs.ToConcurrentDictionary();
var users = new[] { new { Id = 1, Name = "Alice" } };var userDict = users.ToConcurrentDictionary(u => u.Id, u => u.Name);GroupBySafe
Section titled “GroupBySafe”安全地对集合进行分组(支持 null 集合和选择器)。
public static IEnumerable<IGrouping<TKey, TSource>> GroupBySafe<TSource, TKey>( this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)参数:
source: 源集合keySelector: 分组键选择器
返回值: 分组后的集合,如果源为 null 或选择器为 null 则返回空集合
示例:
var numbers = new[] { 1, 2, 3, 4, 5, 6 };var groups = numbers.GroupBySafe(n => n % 2 == 0 ? "偶数" : "奇数");// groups: { "奇数": [1, 3, 5], "偶数": [2, 4, 6] }DistinctSafe
Section titled “DistinctSafe”安全去重(支持 null 集合)。
public static IEnumerable<T> DistinctSafe<T>(this IEnumerable<T> source)返回值: 去重后的集合
WhereSafe
Section titled “WhereSafe”安全筛选(支持 null 集合)。
public static IEnumerable<T> WhereSafe<T>(this IEnumerable<T> source, Func<T, bool> predicate)返回值: 筛选后的集合
SelectSafe
Section titled “SelectSafe”安全投影(支持 null 集合)。
public static IEnumerable<TResult> SelectSafe<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector)返回值: 投影后的集合
OrderBySafe
Section titled “OrderBySafe”安全升序排序(支持 null 集合)。
public static IEnumerable<TSource> OrderBySafe<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)返回值: 排序后的集合
OrderByDescendingSafe
Section titled “OrderByDescendingSafe”安全降序排序(支持 null 集合)。
public static IEnumerable<TSource> OrderByDescendingSafe<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)返回值: 降序排序后的集合
ReverseSafe
Section titled “ReverseSafe”安全反转集合(支持 null 集合)。
public static IEnumerable<T> ReverseSafe<T>(this IEnumerable<T> source)返回值: 反转后的集合
Shuffle
Section titled “Shuffle”随机打乱集合元素顺序。
public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source)返回值: 随机排序后的集合
示例:
var list = Enumerable.Range(1, 10).Shuffle().ToList();// 结果:随机顺序的 1-10RemoveNulls
Section titled “RemoveNulls”移除集合中的 null 元素。
public static IEnumerable<T> RemoveNulls<T>(this IEnumerable<T> source)返回值: 不含 null 的集合
示例:
var list = new List<string?> { "a", null, "b", null, "c" };var nonNull = list.RemoveNulls().ToList(); // ["a", "b", "c"]集合分页。
public static IEnumerable<T> Page<T>(this IEnumerable<T> source, int pageIndex, int pageSize)参数:
source: 集合pageIndex: 页索引(从 0 开始)pageSize: 每页大小
返回值:
- 分页后的集合
示例:
var list = Enumerable.Range(1, 100);var page1 = list.Page(0, 10); // 第1页,包含1-10var page2 = list.Page(1, 10); // 第2页,包含11-20SumSafe
Section titled “SumSafe”集合求和(安全)。
public static int SumSafe(this IEnumerable<int> source)public static double SumSafe(this IEnumerable<double> source)public static decimal SumSafe(this IEnumerable<decimal> source)public static float SumSafe(this IEnumerable<float> source)参数:
source: 集合
返回值:
- 集合元素之和,如果集合为 null 则返回 0
示例:
List<int> list1 = null;List<int> list2 = new List<int> { 1, 2, 3 };
int sum1 = list1.SumSafe(); // 0int sum2 = list2.SumSafe(); // 6AverageSafe
Section titled “AverageSafe”集合平均值(安全)。
public static double AverageSafe(this IEnumerable<int> source)public static double AverageSafe(this IEnumerable<double> source)参数:
source: 集合
返回值:
- 集合元素平均值,如果集合为 null 或空则返回 0
示例:
List<int> list = new List<int> { 1, 2, 3, 4, 5 };
double avg = list.AverageSafe(); // 3MaxBySafe
Section titled “MaxBySafe”获取集合中最大值对应的元素(安全)。
public static TSource MaxBySafe<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector) where TKey : IComparable<TKey>参数:
source: 集合keySelector: 键选择器
返回值:
- 最大值对应的元素,如果集合为空则返回默认值
示例:
var list = new List<Person>{ new Person { Id = 1, Age = 20 }, new Person { Id = 2, Age = 30 }, new Person { Id = 3, Age = 25 }};
var oldest = list.MaxBySafe(x => x.Age); // Id=2, Age=30MinBySafe
Section titled “MinBySafe”获取集合中最小值对应的元素(安全)。
public static TSource MinBySafe<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector) where TKey : IComparable<TKey>返回值:
- 最小值对应的元素,如果集合为空则返回默认值
MaxSafe
Section titled “MaxSafe”集合最大值(安全)。
public static int MaxSafe(this IEnumerable<int> source)public static double MaxSafe(this IEnumerable<double> source)public static decimal MaxSafe(this IEnumerable<decimal> source)public static float MaxSafe(this IEnumerable<float> source)返回值: 集合最大值,如果集合为 null 或空则返回默认值
MinSafe
Section titled “MinSafe”集合最小值(安全)。
public static int MinSafe(this IEnumerable<int> source)public static double MinSafe(this IEnumerable<double> source)public static decimal MinSafe(this IEnumerable<decimal> source)public static float MinSafe(this IEnumerable<float> source)返回值: 集合最小值,如果集合为 null 或空则返回默认值
ForEachSafe
Section titled “ForEachSafe”集合遍历执行操作(安全)。
public static void ForEachSafe<T>(this IEnumerable<T> source, Action<T> action)参数:
source: 集合action: 要执行的操作
示例:
List<int> list = new List<int> { 1, 2, 3 };list.ForEachSafe(x => Console.WriteLine(x));ForEachAsync
Section titled “ForEachAsync”集合遍历执行异步操作。
public static Task ForEachAsync<T>(this IEnumerable<T> source, Func<T, Task> action)参数:
source: 集合action: 要执行的异步操作
返回值:
- Task
示例:
List<string> urls = new List<string> { "url1", "url2", "url3" };await urls.ForEachAsync(async url =>{ await DownloadAsync(url);});ChunkSafe
Section titled “ChunkSafe”集合分块(按指定大小分组,安全)。
public static IEnumerable<IEnumerable<T>> ChunkSafe<T>(this IEnumerable<T> source, int size)参数:
source: 集合size: 每块大小
返回值:
- 分块后的集合
示例:
var list = Enumerable.Range(1, 10);var chunks = list.ChunkSafe(3).ToList();// 结果:[1,2,3], [4,5,6], [7,8,9], [10]集合分批处理。
public static void Batch<T>(this IEnumerable<T> source, int batchSize, Action<IEnumerable<T>> action)参数:
source: 集合batchSize: 批次大小action: 批次处理操作
示例:
var list = Enumerable.Range(1, 100);list.Batch(10, batch =>{ ProcessBatch(batch);});BatchAsync
Section titled “BatchAsync”集合分批异步处理。
public static async Task BatchAsync<T>(this IEnumerable<T> source, int batchSize, Func<IEnumerable<T>, Task> action)参数:
source: 集合batchSize: 批次大小action: 批次异步处理操作
示例:
var list = Enumerable.Range(1, 100);await list.BatchAsync(10, async batch =>{ await ProcessBatchAsync(batch);});AllSafe
Section titled “AllSafe”判断集合是否全部满足条件(安全)。
public static bool AllSafe<T>(this IEnumerable<T> source, Func<T, bool> predicate)参数:
source: 集合predicate: 条件谓词
返回值:
- 如果集合为 null 或所有元素都满足条件返回 true;否则返回 false
示例:
List<int> list = new List<int> { 2, 4, 6, 8 };bool result = list.AllSafe(x => x % 2 == 0); // trueAnySafe
Section titled “AnySafe”判断集合是否有任意元素满足条件(安全)。
public static bool AnySafe<T>(this IEnumerable<T> source, Func<T, bool> predicate)参数:
source: 集合predicate: 条件谓词
返回值:
- 如果集合不为 null 且有任意元素满足条件返回 true;否则返回 false
示例:
List<int> list = new List<int> { 1, 2, 3 };bool result = list.AnySafe(x => x > 2); // trueSequenceEqualSafe
Section titled “SequenceEqualSafe”判断两个集合是否相等(顺序和元素都相同,安全)。
public static bool SequenceEqualSafe<T>(this IEnumerable<T> first, IEnumerable<T> second)参数:
first: 第一个集合second: 第二个集合
返回值:
- 如果两个集合相等返回 true;否则返回 false
示例:
var list1 = new List<int> { 1, 2, 3 };var list2 = new List<int> { 1, 2, 3 };bool result = list1.SequenceEqualSafe(list2); // trueContainsSameElements
Section titled “ContainsSameElements”判断两个集合是否包含相同的元素(忽略顺序)。
public static bool ContainsSameElements<T>(this IEnumerable<T> first, IEnumerable<T> second)参数:
first: 第一个集合second: 第二个集合
返回值:
- 如果两个集合包含相同的元素返回 true;否则返回 false
示例:
var list1 = new List<int> { 1, 2, 3 };var list2 = new List<int> { 3, 2, 1 };bool result = list1.ContainsSameElements(list2); // trueContainsNull
Section titled “ContainsNull”判断集合是否包含 null 元素。
public static bool ContainsNull<T>(this IEnumerable<T> source)参数:
source: 集合
返回值:
- 如果集合包含 null 元素返回 true;否则返回 false
示例:
var list = new List<string> { "a", null, "b" };bool result = list.ContainsNull(); // trueConcatSafe
Section titled “ConcatSafe”合并两个集合(安全)。
public static IEnumerable<T> ConcatSafe<T>(this IEnumerable<T> first, IEnumerable<T> second)参数:
first: 第一个集合second: 第二个集合
返回值:
- 合并后的集合
示例:
var list1 = new List<int> { 1, 2 };var list2 = new List<int> { 3, 4 };var result = list1.ConcatSafe(list2); // [1, 2, 3, 4]ConcatMany
Section titled “ConcatMany”合并多个集合。
public static IEnumerable<T> ConcatMany<T>(params IEnumerable<T>[] sources)参数:
sources: 集合数组
返回值:
- 合并后的集合
示例:
var list1 = new List<int> { 1 };var list2 = new List<int> { 2 };var list3 = new List<int> { 3 };var result = EnumerableExtensions.ConcatMany(list1, list2, list3); // [1, 2, 3]IntersectSafe
Section titled “IntersectSafe”获取两个集合的交集(安全)。
public static IEnumerable<T> IntersectSafe<T>(this IEnumerable<T> first, IEnumerable<T> second)参数:
first: 第一个集合second: 第二个集合
返回值:
- 交集
示例:
var list1 = new List<int> { 1, 2, 3 };var list2 = new List<int> { 2, 3, 4 };var result = list1.IntersectSafe(list2); // [2, 3]UnionSafe
Section titled “UnionSafe”获取两个集合的并集(安全)。
public static IEnumerable<T> UnionSafe<T>(this IEnumerable<T> first, IEnumerable<T> second)参数:
first: 第一个集合second: 第二个集合
返回值:
- 并集
示例:
var list1 = new List<int> { 1, 2 };var list2 = new List<int> { 2, 3 };var result = list1.UnionSafe(list2); // [1, 2, 3]ExceptSafe
Section titled “ExceptSafe”获取两个集合的差集(安全)。
public static IEnumerable<T> ExceptSafe<T>(this IEnumerable<T> first, IEnumerable<T> second)参数:
first: 第一个集合second: 第二个集合
返回值:
- 差集(在第一个集合但不在第二个集合的元素)
示例:
var list1 = new List<int> { 1, 2, 3 };var list2 = new List<int> { 2, 3, 4 };var result = list1.ExceptSafe(list2); // [1]JoinToString
Section titled “JoinToString”将集合元素连接为字符串。
public static string JoinToString<T>(this IEnumerable<T> source, string separator = ",")public static string JoinToString<T>(this IEnumerable<T> source, Func<T, string> selector, string separator = ",")参数:
source: 集合separator: 分隔符,默认为逗号selector: 字符串选择器(可选)
返回值:
- 连接后的字符串
示例:
var list = new List<int> { 1, 2, 3 };string result1 = list.JoinToString(); // "1,2,3"string result2 = list.JoinToString(x => $"#{x}", " | "); // "#1 | #2 | #3"ForEachIndexed
Section titled “ForEachIndexed”集合遍历执行操作(带索引)。
public static void ForEachIndexed<T>(this IEnumerable<T> source, Action<T, int> action)参数:
source: 集合action: 操作委托,参数为元素和索引
示例:
var list = new List<string> { "a", "b", "c" };list.ForEachIndexed((item, index) => Console.WriteLine($"{index}: {item}"));// 输出: 0: a, 1: b, 2: cICollection 扩展
Section titled “ICollection 扩展”AddSafe
Section titled “AddSafe”安全添加元素到集合。
public static void AddSafe<T>(this ICollection<T> collection, T item)参数:
collection: 集合item: 要添加的元素
示例:
List<int> list = null;list.AddSafe(1); // 不会抛出异常RemoveSafe
Section titled “RemoveSafe”安全移除元素。
public static void RemoveSafe<T>(this ICollection<T> collection, T item)参数:
collection: 集合item: 要移除的元素
示例:
var list = new List<int> { 1, 2, 3 };list.RemoveSafe(2); // [1, 3]ClearSafe
Section titled “ClearSafe”安全清空集合。
public static void ClearSafe<T>(this ICollection<T> collection)示例:
List<int> list = null;list.ClearSafe(); // 不会抛出异常AddRangeSafe
Section titled “AddRangeSafe”批量添加元素(安全)。
public static void AddRangeSafe<T>(this ICollection<T> collection, IEnumerable<T> items)参数:
collection: 集合items: 要添加的元素集合
示例:
List<int> list = new List<int> { 1, 2 };list.AddRangeSafe(new[] { 3, 4, 5 });// list: [1, 2, 3, 4, 5]RemoveRangeSafe
Section titled “RemoveRangeSafe”批量移除元素(安全)。
public static void RemoveRangeSafe<T>(this ICollection<T> collection, IEnumerable<T> items)参数:
collection: 集合items: 要移除的元素集合
示例:
var list = new List<int> { 1, 2, 3, 4, 5 };list.RemoveRangeSafe(new[] { 2, 4 });// list: [1, 3, 5]- 数据处理 - 安全处理可能为空的集合数据,避免 null 异常
- Web API - 处理请求和响应数据的集合操作
- 数据转换 - 在各种数据结构(DataTable、Dictionary、ConcurrentDictionary)之间转换
- 分页处理 - 对数据集合进行分页处理
- 统计分析 - 对集合数据进行求和、平均值、最大值等统计计算
- 业务逻辑 - 过滤、排序、分组等业务操作
- 并发处理 - 转换为线程安全的 ConcurrentDictionary
- 数据清洗 - 去重、去除 null 值、批量处理等
- 所有方法都是扩展方法,需要通过集合实例调用
- 带有 “Safe” 后缀的方法对 null 值做了安全处理,不会抛出异常
- 大部分方法在集合为 null 时会返回空集合或默认值,而不是抛出异常
Page<T>()方法使用 0 作为起始页索引Chunk<T>()方法使用延迟执行,内存效率较高- 统计方法在集合为空时会返回默认值(通常为 0),而不是抛出异常
- 转换方法在选择器委托为 null 时,使用默认委托进行处理
- 集合操作方法都进行了空值有效性检查,使代码更健壮