diff --git a/src/DotNet.MultiMap/MultiMapHashSet.cs b/src/DotNet.MultiMap/MultiMapHashSet.cs index 0d26010..8b96bd7 100644 --- a/src/DotNet.MultiMap/MultiMapHashSet.cs +++ b/src/DotNet.MultiMap/MultiMapHashSet.cs @@ -96,14 +96,13 @@ public MultiMapHashSet(IEnumerable>> collecti /// true if the value has been map to the specified key element; otherwise, false. public bool TryToAddMapping(TKey key, TValue val) { - if (ContainsKey(key)) + if (TryGetValue(key, out var set)) { - var set = this[key]; return set.Add(val); } - var tmp = new HashSet(); + var tmp = new HashSet { val }; Add(key, tmp); - return tmp.Add(val); + return true; } /// @@ -115,9 +114,8 @@ public bool TryToAddMapping(TKey key, TValue val) public bool TryToRemoveMapping(TKey key, TValue val) { bool result = false; - if (ContainsKey(key)) + if (TryGetValue(key, out var set)) { - var set = this[key]; result = set.Remove(val); if (set.Count == 0) { @@ -135,13 +133,8 @@ public bool TryToRemoveMapping(TKey key, TValue val) /// the number of links (duplicates). public int ContainsMapping(TKey key, TValue val) { - if (ContainsKey(key)) - { - var set = this[key]; - if (set.Contains(val)) - { - return 1; - } + if (TryGetValue(key, out var set) && set.Contains(val)) { + return 1; } return 0; } diff --git a/src/DotNet.MultiMap/MultiMapList.cs b/src/DotNet.MultiMap/MultiMapList.cs index b643f5e..9af8856 100644 --- a/src/DotNet.MultiMap/MultiMapList.cs +++ b/src/DotNet.MultiMap/MultiMapList.cs @@ -99,16 +99,14 @@ public MultiMapList(IEnumerable>> collection, IE /// true if the value has been map to the specified key element; otherwise, false. public bool TryToAddMapping(TKey key, TValue val) { - if (ContainsKey(key)) + if (TryGetValue(key, out var set)) { - var set = this[key]; set.Add(val); } else { - var tmp = new List(); + var tmp = new List { val }; Add(key, tmp); - tmp.Add(val); } return true; } @@ -122,12 +120,10 @@ public bool TryToAddMapping(TKey key, TValue val) public bool TryToRemoveMapping(TKey key, TValue val) { bool result = false; - if (ContainsKey(key)) + if (TryGetValue(key, out var set)) { - var set = this[key]; result = set.Remove(val); - if (set.Count == 0) - { + if (set.Count == 0) { Remove(key); } } @@ -142,9 +138,8 @@ public bool TryToRemoveMapping(TKey key, TValue val) /// the number of links (duplicates). public int ContainsMapping(TKey key, TValue val) { - if (ContainsKey(key)) + if (TryGetValue(key, out var set)) { - var set = this[key]; return set.Count((v) => v.Equals(val)); } return 0;