|
|
@ -1006,6 +1006,46 @@ namespace Apewer |
|
|
|
|
|
|
|
#endregion
|
|
|
|
|
|
|
|
#region Group
|
|
|
|
|
|
|
|
/// <summary>对元素按指定的键分组。</summary>
|
|
|
|
/// <param name="items"></param>
|
|
|
|
/// <param name="keyGetter"></param>
|
|
|
|
public static Dictionary<TKey, TValue[]> Group<TKey, TValue>(this IEnumerable<TValue> items, Func<TValue, TKey> keyGetter) |
|
|
|
{ |
|
|
|
if (items == null) throw new ArgumentNullException(nameof(items)); |
|
|
|
if (keyGetter == null) throw new ArgumentNullException(nameof(keyGetter)); |
|
|
|
|
|
|
|
var dict = new SortedDictionary<TKey, List<TValue>>(); |
|
|
|
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<TValue>(); |
|
|
|
list.Add(item); |
|
|
|
dict.Add(key, list); |
|
|
|
} |
|
|
|
} |
|
|
|
|
|
|
|
var result = new Dictionary<TKey, TValue[]>(dict.Count); |
|
|
|
foreach (var kvp in dict) |
|
|
|
{ |
|
|
|
result.Add(kvp.Key, kvp.Value.ToArray()); |
|
|
|
} |
|
|
|
return result; |
|
|
|
} |
|
|
|
|
|
|
|
#endregion
|
|
|
|
|
|
|
|
} |
|
|
|
|
|
|
|
} |
|
|
|