Click or drag to resize

RankedMapTKey, TValue Class

Represents a collection of key/value pairs with nondistinct keys that can be accessed in sort order or by index.
Inheritance Hierarchy
SystemObject
  Kaos.CollectionsBtreeTKey
    Kaos.CollectionsRankedMapTKey, TValue

Namespace:  Kaos.Collections
Assembly:  KaosCollections (in KaosCollections.dll) Version: 4.2.0.0
Syntax
C#
[SerializableAttribute]
public class RankedMap<TKey, TValue> : Btree<TKey>, 
	ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, 
	IEnumerable, ICollection, IReadOnlyCollection<KeyValuePair<TKey, TValue>>, 
	ISerializable, IDeserializationCallback

Type Parameters

TKey
The type of the keys in the map.
TValue
The type of the values in the map.

The RankedMapTKey, TValue type exposes the following members.

Constructors
  NameDescription
Public methodRankedMapTKey, TValue
Initializes a new map instance using the default key comparer.
Public methodRankedMapTKey, TValue(ICollectionKeyValuePairTKey, TValue)
Initializes a new map instance that contains key/value pairs copied from the supplied map and sorted by the default comparer.
Public methodCode exampleRankedMapTKey, TValue(IComparerTKey)
Initializes a new map instance using the supplied key comparer.
Public methodRankedMapTKey, TValue(ICollectionKeyValuePairTKey, TValue, IComparerTKey)
Initializes a new map instance that contains key/value pairs copied from the supplied map and sorted by the supplied comparer.
Protected methodRankedMapTKey, TValue(SerializationInfo, StreamingContext)
Initializes a new map instance that contains serialized data.
Top
Properties
Methods
  NameDescription
Public methodCode exampleAdd
Adds an element with the supplied key and value.
Public methodClear
Removes all elements from the map.
Public methodCode exampleContainsKey
Determines whether the map contains the supplied key.
Public methodContainsValue
Determines whether the map contains the supplied value.
Public methodCopyTo
Copies the map to a compatible array, starting at the supplied position.
Public methodElementAt
Gets the key/value pair at the supplied index.
Public methodElementAtOrDefault
Gets the key/value pair at the supplied index or the default if the index is out of range.
Public methodElementsBetween
Returns an enumerator that iterates over a range with the supplied bounds.
Public methodElementsBetweenIndexes
Returns an enumerator that iterates over a range with the supplied index bounds.
Public methodElementsFrom
Returns an enumerator that iterates over a range with the supplied lower bound.
Public methodEquals
Determines whether the specified object is equal to the current object.
(Inherited from Object.)
Protected methodFinalize
Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection.
(Inherited from Object.)
Public methodFirst
Gets the element with the lowest sorted key in the map.
Public methodGetEnumerator
Gets an enumerator that iterates thru the map.
Public methodGetHashCode
Serves as the default hash function.
(Inherited from Object.)
Protected methodGetObjectData
Returns the data needed to serialize the map.
Public methodGetType
Gets the Type of the current instance.
(Inherited from Object.)
Public methodIndexOfKey
Gets the index of the first element with the supplied key.
Public methodIndexOfValue
Gets the index of the first element with the supplied value.
Public methodLast
Gets the element with the highest sorted key in the map.
Protected methodMemberwiseClone
Creates a shallow copy of the current Object.
(Inherited from Object.)
Protected methodOnDeserialization
Implements the deserialization callback and raises the deserialization event when completed.
Public methodCode exampleRemove(TKey)
Removes all elements with the supplied key from the map.
Public methodCode exampleRemove(TKey, Int32)
Removes a supplied number of elements with the supplied key from the map.
Public methodRemoveAll
Removes all elements with keys in the supplied collection from the map.
Public methodRemoveAt
Removes an element at the supplied index from the map.
Public methodRemoveRange
Removes an index range of elements from the map.
Public methodRemoveWhere
Removes all elements from the map that match the condition defined by the supplied key-parameterized predicate.
Public methodRemoveWhereElement
Removes all elements from the map that match the condition defined by the supplied key/value-parameterized predicate.
Public methodReverse
Returns an enumerator that iterates thru the map in reverse order.
Public methodCode exampleSkip
Bypasses a supplied number of elements and yields the remaining elements.
Public methodSkipWhile(FuncKeyValuePairTKey, TValue, Boolean)
Bypasses elements as long as a supplied condition is true and yields the remaining elements.
Public methodSkipWhile(FuncKeyValuePairTKey, TValue, Int32, Boolean)
Bypasses elements as long as a supplied index-based condition is true and yields the remaining elements.
Public methodToString
Returns a string that represents the current object.
(Inherited from Object.)
Public methodTryGetGreaterThan
Gets an element with the least key greater than the supplied key.
Public methodTryGetGreaterThanOrEqual
Gets an element with the least key greater than or equal to the supplied key.
Public methodTryGetLessThan
Gets an element with the greatest key less than the supplied key.
Public methodTryGetLessThanOrEqual
Gets an element with the greatest key less than or equal to the supplied key.
Top
Explicit Interface Implementations
  NameDescription
Explicit interface implementationPrivate methodICollectionKeyValuePairTKey, TValueAdd
Adds an element with the supplied key/value pair.
Explicit interface implementationPrivate methodICollectionKeyValuePairTKey, TValueContains
Determines whether the map contains the supplied key/value pair.
Explicit interface implementationPrivate methodICollectionCopyTo
Copies the elements of the map to an array, starting at the supplied array index.
Explicit interface implementationPrivate methodIEnumerableKeyValuePairTKey, TValueGetEnumerator
Gets an enumerator that iterates thru the map.
Explicit interface implementationPrivate methodIEnumerableGetEnumerator
Gets an enumerator that iterates thru the collection.
Explicit interface implementationPrivate methodISerializableGetObjectData
Returns the data needed to serialize the map.
Explicit interface implementationPrivate propertyICollectionKeyValuePairTKey, TValueIsReadOnly
Indicates that this collection may be modified.
Explicit interface implementationPrivate propertyICollectionIsSynchronized
Indicates that the collection is not thread safe.
Explicit interface implementationPrivate methodIDeserializationCallbackOnDeserialization
Implements the deserialization callback and raises the deserialization event when completed.
Explicit interface implementationPrivate methodICollectionKeyValuePairTKey, TValueRemove
Deletes all occurrences of the supplied key and its associated value from the collection.
Explicit interface implementationPrivate propertyICollectionSyncRoot
Gets an object that can be used to synchronize access to the collection.
Top
Examples

First is a basic example of this class.

C#
using System;
using Kaos.Collections;

namespace ExampleApp
{
    class RmExample02
    {
        static void Main()
        {
            var map = new RankedMap<char,int>();
            var input = "this is it";

            for (int pos = 0; pos < input.Length; ++pos)
                if (! Char.IsWhiteSpace (input[pos]))
                    map.Add (input[pos], pos);

            foreach (var kv in map)
                Console.WriteLine (kv);
        }

        /* Output:

        [h, 1]
        [i, 2]
        [i, 5]
        [i, 8]
        [s, 3]
        [s, 6]
        [t, 0]
        [t, 9]

        */
    }
}

Next is a larger example showing some common operations of this class.

C#
using System;
using Kaos.Collections;

namespace ExampleApp
{
    class RmExample01
    {
        static void Main()
        {
            // Keys will compare case insensitive with this constructor.
            var fmt = new RankedMap<string,string> (StringComparer.InvariantCultureIgnoreCase);

            fmt.Add ("csv", "Comma Separated Values");
            fmt.Add ("DAT", "dBase II data file");
            fmt.Add ("dat", "Sony Digital Audio Tape");

            fmt.Add ("qt", "QuickTime movie clip");
            fmt.Add ("jpeg", "JPEG bitmap image format");
            fmt.Add ("sln", "Blend for Visual Studio");
            fmt.Add ("sln", "Visual Studio 2017");

            if (fmt.ContainsKey ("jpeg"))
                fmt.Add ("jpg", "JPEG bitmap image format");

            if (fmt.Keys.GetCount ("sln") > 1)
                fmt.Add ("sln", "Visual Studio Version Selector");

            // When you use foreach to enumerate map elements,
            // each element is retrieved as a KeyValuePair.
            Console.WriteLine ("All map elements:");
            foreach (System.Collections.Generic.KeyValuePair<string,string> pair in fmt)
                Console.WriteLine ($"  Key = {pair.Key}, Value = {pair.Value}");

            Console.WriteLine ($"\nDistinct format count: {fmt.Keys.GetDistinctCount()}");
            Console.WriteLine ($"Total format count: {fmt.Count}");

            Console.WriteLine ("\nRemove all sln format occurrences...");
            int removed = fmt.Remove ("sln", Int32.MaxValue);
            Console.WriteLine ($"Items removed: {removed}");

            Console.WriteLine ("Remove qt format...");
            fmt.Remove ("qt");

            // To get the keys alone, use the Keys property.
            RankedMap<string,string>.KeyCollection keys = fmt.Keys;

            // The items of a KeyCollection have the type specified for the map keys.
            Console.WriteLine ("\nKeys:");
            foreach (string x in keys)
                Console.WriteLine ($"  {x}");

            // To get the values alone, use the Values property.
            RankedMap<string,string>.ValueCollection values = fmt.Values;

            Console.WriteLine ("\nValues:");
            foreach (string x in values)
                Console.WriteLine ($"  {x}");
        }

        /* Output:

        All map elements:
          Key = csv, Value = Comma Separated Values
          Key = DAT, Value = dBase II data file
          Key = dat, Value = Sony Digital Audio Tape
          Key = jpeg, Value = JPEG bitmap image format
          Key = jpg, Value = JPEG bitmap image format
          Key = qt, Value = QuickTime movie clip
          Key = sln, Value = Blend for Visual Studio
          Key = sln, Value = Visual Studio 2017
          Key = sln, Value = Visual Studio Version Selector

        Distinct format count: 6
        Total format count: 9

        Remove all sln format occurrences...
        Items removed: 3
        Remove qt format...

        Keys:
          csv
          DAT
          dat
          jpeg
          jpg

        Values:
          Comma Separated Values
          dBase II data file
          Sony Digital Audio Tape
          JPEG bitmap image format
          JPEG bitmap image format

        */
    }
}

Last is an example showing binary serialization round tripped.

Note: Serialization is not supported in .NET Standard 1.0.

C#
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using Kaos.Collections;

namespace ExampleApp
{
    [Serializable]
    public class PlayerComparer : Comparer<Player>
    {
        public override int Compare (Player x, Player y)
        {
            int cp = String.Compare (x.Clan, y.Clan);
            return cp != 0 ? cp : String.Compare (x.Name, y.Name);
        }
    }

    [Serializable]
    public class PlayerMap : RankedMap<Player,int>
    {
        public string Game { get; set; }

        public PlayerMap() : base (new PlayerComparer())
        { }

        public PlayerMap (SerializationInfo info, StreamingContext context) : base (info, context)
        {
            this.Game = info.GetString ("Game");
        }

        protected override void GetObjectData (SerializationInfo info, StreamingContext context)
        {
            base.GetObjectData (info, context);
            info.AddValue ("Game", Game, typeof (string));
        }
    }

    [Serializable]
    public class Player : ISerializable
    {
        public string Clan { get; private set; }
        public string Name { get; private set; }

        public Player (string clan, string name)
        { this.Clan = clan; this.Name = name; }

        protected Player (SerializationInfo info, StreamingContext context)
        {
            this.Clan = (string) info.GetValue ("Clan", typeof (string));
            this.Name = (string) info.GetValue ("Name", typeof (string));
        }

        public virtual void GetObjectData (SerializationInfo info, StreamingContext context)
        {
            info.AddValue ("Clan", Clan, typeof (string));
            info.AddValue ("Name", Name, typeof (string));
        }

        public override string ToString() => Clan + "." + Name;
    }


    class RmExample05
    {
        static void Main()
        {
            string fileName = "MapScores.bin";
            var map1 = new PlayerMap() { Game = "Day of Defeat" };
            map1.Add (new Player ("GG", "Floyd"), 11);
            map1.Add (new Player (null, "Player"), 22);
            map1.Add (new Player ("A1", "Betty"), 44);
            map1.Add (new Player ("GG", "Edwin"), 66);
            map1.Add (new Player (null, "Player"), 77);

            IFormatter formatter = new BinaryFormatter();
            using (var fs = new FileStream (fileName, FileMode.Create))
            { formatter.Serialize (fs, map1); }

            Console.WriteLine ($"Wrote {map1.Count} key/value pairs.\n");

            PlayerMap map2 = null;
            using (var fs = new FileStream (fileName, FileMode.Open))
            { map2 = (PlayerMap) formatter.Deserialize (fs); }

            Console.WriteLine ("Read back:");
            Console.WriteLine ($"Game = {map2.Game}");
            Console.WriteLine ("Players:");
            foreach (var kv in map2)
                Console.WriteLine ($"  {kv}");
        }

        /* Output:

        Wrote 5 key/value pairs.

        Read back:
        Game = Day of Defeat
        Players:
          [.Player, 22]
          [.Player, 77]
          [A1.Betty, 44]
          [GG.Edwin, 66]
          [GG.Floyd, 11]

        */
    }
}
See Also