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 + } }