From 21df26941995c62936bd78c26fe38d01ae52d846 Mon Sep 17 00:00:00 2001 From: Elivo Date: Thu, 24 Apr 2025 13:19:35 +0800 Subject: [PATCH] =?UTF-8?q?CollectionUtility=EF=BC=9AIEnumerable.Map=20?= =?UTF-8?q?=E6=89=A9=E5=B1=95=E6=96=B9=E6=B3=95=E5=A2=9E=E5=8A=A0=E9=87=8D?= =?UTF-8?q?=E8=BD=BD=EF=BC=8C=E6=8F=90=E4=BE=9B=20index=20=E5=8F=82?= =?UTF-8?q?=E6=95=B0=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Apewer/CollectionUtility.cs | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) 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();