diff --git a/Apewer/CollectionUtility.cs b/Apewer/CollectionUtility.cs index d0ead3c..90f14ab 100644 --- a/Apewer/CollectionUtility.cs +++ b/Apewer/CollectionUtility.cs @@ -731,13 +731,27 @@ namespace Apewer if (selector == null) throw new ArgumentNullException(nameof(selector)); if (collection == null) return new TOut[0]; + return Map(collection, (item, index) => selector.Invoke(item)); + } + + /// 遍历集合,转换元素,生成新数组。 + /// 输入的元素类型。 + /// 输出的元素类型。 + /// 要遍历的集合。 + /// 转换程序。 + /// 新数组的元素类型。 + public static TOut[] Map(this IEnumerable collection, Func selector) + { + if (selector == null) throw new ArgumentNullException(nameof(selector)); + if (collection == null) return new TOut[0]; + if (collection is TIn[] array) { var count = array.Length; var result = new TOut[count]; for (var i = 0; i < count; i++) { - result[i] = selector.Invoke(array[i]); + result[i] = selector.Invoke(array[i], i); } return result; } @@ -753,7 +767,7 @@ namespace Apewer capacity += 1024; list.Capacity += capacity; } - list.Add(selector.Invoke(item)); + list.Add(selector.Invoke(item, count)); count += 1; } return list.ToArray();