From 61001a845473c3646c08c84a6cd42e16d2a57e49 Mon Sep 17 00:00:00 2001 From: Elivo Date: Wed, 30 Jul 2025 21:11:20 +0800 Subject: [PATCH] =?UTF-8?q?CollectionUtility=EF=BC=8C=E5=A2=9E=E5=8A=A0=20?= =?UTF-8?q?Group=20=E6=96=B9=E6=B3=95=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Apewer/CollectionUtility.cs | 40 +++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/Apewer/CollectionUtility.cs b/Apewer/CollectionUtility.cs index fb917c1..ece8aab 100644 --- a/Apewer/CollectionUtility.cs +++ b/Apewer/CollectionUtility.cs @@ -1006,6 +1006,46 @@ namespace Apewer #endregion + #region Group + + /// 对元素按指定的键分组。 + /// + /// + public static Dictionary Group(this IEnumerable items, Func keyGetter) + { + if (items == null) throw new ArgumentNullException(nameof(items)); + if (keyGetter == null) throw new ArgumentNullException(nameof(keyGetter)); + + var dict = new SortedDictionary>(); + foreach (var item in items) + { + if (item.IsNull()) continue; + + var key = keyGetter.Invoke(item); + if (key.IsNull()) continue; + + if (dict.TryGetValue(key, out var list)) + { + list.Add(item); + } + else + { + list = new List(); + list.Add(item); + dict.Add(key, list); + } + } + + var result = new Dictionary(dict.Count); + foreach (var kvp in dict) + { + result.Add(kvp.Key, kvp.Value.ToArray()); + } + return result; + } + + #endregion + } }