J’ai besoin d’un équivalent au std::multimap
de c ++ dans C-sharp. Existe-t-il dans la bibliothèque standard?
Parce que c’est presque Noël 🙂
////////////////////////////////////////////////////////////////////// // Algorithmia is (c) 2008 Solutions Design. All rights reserved. // http://www.sd.nl ////////////////////////////////////////////////////////////////////// // COPYRIGHTS: // Copyright (c) 2008 Solutions Design. All rights reserved. // // The Algorithmia library sourcecode and its accompanying tools, tests and support code // are released under the following license: (BSD2) // ---------------------------------------------------------------------- // Redissortingbution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // 1) Redissortingbutions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // 2) Redissortingbutions in binary form must reproduce the above copyright notice, this list of // conditions and the following disclaimer in the documentation and/or other materials // provided with the dissortingbution. // // THIS SOFTWARE IS PROVIDED BY SOLUTIONS DESIGN ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A // PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SOLUTIONS DESIGN OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT // NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR // BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE // USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // The views and conclusions contained in the software and documentation are those of the authors // and should not be interpreted as representing official policies, either expressed or implied, // of Solutions Design. // ////////////////////////////////////////////////////////////////////// // Consortingbuters to the code: // - Frans Bouma [FB] ////////////////////////////////////////////////////////////////////// using System; using System.Collections.Generic; using System.Linq; using System.Text; using SD.Tools.Algorithmia.UtilityClasses; namespace SD.Tools.Algorithmia.GeneralDataStructures { /// /// Extension to the normal Dictionary. This class can store more than one value for every key. It keeps a HashSet for every Key value. /// Calling Add with the same Key and multiple values will store each value under the same Key in the Dictionary. Obtaining the values /// for a Key will return the HashSet with the Values of the Key. /// /// The type of the key. /// The type of the value. public class MultiValueDictionary : Dictionary> { /// /// Initializes a new instance of the class. /// public MultiValueDictionary() : base() { } /// /// Adds the specified value under the specified key /// /// The key. /// The value. public void Add(TKey key, TValue value) { ArgumentVerifier.CantBeNull(key, "key"); HashSet container = null; if(!this.TryGetValue(key, out container)) { container = new HashSet (); base.Add(key, container); } container.Add(value); } /// /// Determines whether this dictionary contains the specified value for the specified key /// /// The key. /// The value. /// true if the value is stored for the specified key in this dictionary, false otherwise public bool ContainsValue(TKey key, TValue value) { ArgumentVerifier.CantBeNull(key, "key"); bool toReturn = false; HashSet values = null; if(this.TryGetValue(key, out values)) { toReturn = values.Contains(value); } return toReturn; } /// /// Removes the specified value for the specified key. It will leave the key in the dictionary. /// /// The key. /// The value. public void Remove(TKey key, TValue value) { ArgumentVerifier.CantBeNull(key, "key"); HashSet container = null; if(this.TryGetValue(key, out container)) { container.Remove(value); if(container.Count <= 0) { this.Remove(key); } } } /// /// Merges the specified multivaluedictionary into this instance. /// /// To merge with. public void Merge(MultiValueDictionary toMergeWith) { if(toMergeWith==null) { return; } foreach(KeyValuePair> pair in toMergeWith) { foreach(TValue value in pair.Value) { this.Add(pair.Key, value); } } } /// /// Gets the values for the key specified. This method is useful if you want to avoid an exception for key value resortingeval and you can't use TryGetValue /// (eg in lambdas) /// /// The key. /// if set to true and the key isn't found, an empty hashset is returned, otherwise, if the key isn't found, null is returned /// /// This method will return null (or an empty set if returnEmptySet is true) if the key wasn't found, or /// the values if key was found. /// public HashSet GetValues(TKey key, bool returnEmptySet) { HashSet toReturn = null; if(!base.TryGetValue(key, out toReturn) && returnEmptySet) { toReturn = new HashSet (); } return toReturn; } } }
ILookup peut être assez bon pour vous – mais malheureusement, il n’y a pas d’implémentations publiques. En gros, vous devez passer par Enumerable.ToLookup , autant que je sache. Cela signifie que c’est une sorte de carte “build once” – vous ne pouvez pas y append plus tard. Cependant, si c’est tout ce dont vous avez besoin, il est utile de pouvoir utiliser les éléments intégrés.
Dans .NET 3.5, il existe un ILookup<,>
qui représente ceci. L’implémentation régulière ( Lookup<,>
) est immuable, mais j’ai un EditableLookup<,>
dans MiscUtil qui devrait faire l’affaire.
vous pouvez essayer ceci
Classe générique C # MultiMap
http://dotnetperls.com/multimap
Implémentation multimap très simple.
Vous pouvez trouver ac # multimap collection @ http://code.google.com/p/self-balancing-avl-tree/ . Il est basé sur un arbre AVL à équilibrage automatique qui est également inclus avec le code.
Pensez à utiliser BMultiMap
si votre collection dans son ensemble est grande. Cela économise beaucoup de mémoire par rapport au Dictionary
, surtout si le nombre de valeurs associées à chaque touche est souvent faible.