diff --git a/Extensions/EnumerableExtensions.cs b/Extensions/EnumerableExtensions.cs index c2ff952..edfef2c 100644 --- a/Extensions/EnumerableExtensions.cs +++ b/Extensions/EnumerableExtensions.cs @@ -176,8 +176,40 @@ public static class EnumerableExtensions { return result; } + /// + /// 尝试从字典中获取某项,如果该项不存在,则返回默认值。 + /// + public static TValue GetOrDefault(this IDictionary dict, TKey key, TValue defaultValue = default!) => + dict.TryGetValue(key, out var result) ? result : defaultValue; + + /// + /// 将值添加到字典的对应项的列表中。 + /// + public static void AddIntoValueCollection(this IDictionary> dict, TKey key, TValue value) { + if (dict.TryGetValue(key, out var collection)) { + collection.Add(value); + } else { + dict.Add(key, [value]); + } + } + #endregion + /// + /// 将 枚举值解包为它包含的单一 Flag 成员的集合。 + /// 建议仅对没有极端值的正数枚举使用。 + /// + /// + /// 会跳过:0、非 2 的幂的值、不在枚举值中的数、组合值、对应同一个枚举项的多个别名。 + /// + public static IEnumerable Flags(this T value) where T : struct, Enum { + foreach (var element in Enum.GetValues(typeof(T)).Cast().Distinct()) { + var number = Convert.ToInt64(element); + if (number == 0 || (number & (number - 1)) != 0) continue; // 跳过 0 和非 2 的幂的值 + if (value.HasFlag(element)) yield return element; + } + } + /// /// 判断集合是否有且仅有一个元素。 /// 在输入 null 时返回 false。