Click or drag to resize

RankedBagT Class

Represents a collection of nondistinct items that can be accessed in sort order or by index.
Inheritance Hierarchy
SystemObject
  Kaos.CollectionsBtreeT
    Kaos.CollectionsRankedBagT

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

Type Parameters

T
The type of the items in the bag.

The RankedBagT type exposes the following members.

Constructors
  NameDescription
Public methodRankedBagT
Initializes a new bag instance that uses the default comparer.
Public methodCode exampleRankedBagT(IComparerT)
Initializes a new bag instance that uses the supplied comparer.
Public methodCode exampleRankedBagT(IEnumerableT)
Initializes a new bag instance that contains items copied from the supplied collection.
Public methodRankedBagT(IEnumerableT, IComparerT)
Initializes a new bag instance that contains items copied from the supplied collection.
Protected methodRankedBagT(SerializationInfo, StreamingContext)
Initializes a new bag instance that contains serialized data.
Top
Properties
  NameDescription
Public propertyCapacity
Gets or sets the order of the underlying B+ tree structure.
(Inherited from BtreeT.)
Public propertyComparer
Returns a wrapper of the method used to order items in the bag.
Public propertyCount
Gets the total number of occurrences of all items in the bag.
Public propertyMax
Gets the maximum item in the bag per the comparer.
Public propertyMin
Gets the minimum item in the bag per the comparer.
Top
Methods
  NameDescription
Public methodAdd(T)
Adds an item to the bag.
Public methodAdd(T, Int32)
Adds a supplied number of occurrences of the supplied item to the bag.
Public methodClear
Removes all items from the bag.
Public methodContains
Determines whether the bag contains the supplied item.
Public methodContainsAll
Determines whether the bag is a subset of the supplied collection.
Public methodCopyTo(T)
Copies the items to a compatible array.
Public methodCopyTo(T, Int32)
Copies the items to a compatible array, starting at the supplied position.
Public methodCopyTo(T, Int32, Int32)
Copies a supplied number of items to a compatible array, starting at the supplied position.
Public methodDistinct
Returns an enumerator that iterates thru the distinct items of the bag in sort order.
Public methodElementAt
Gets the item at the supplied index.
Public methodElementAtOrDefault
Gets the item at the supplied index or the default if the index is out of range.
Public methodCode exampleElementsBetween
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 minimum item in the bag per the comparer.
Public methodGetCount
Returns the number of occurrences of the supplied item in the bag.
Public methodGetDistinctCount
Returns the number of distinct items in the bag.
Public methodGetEnumerator
Returns an enumerator that iterates thru the bag.
Public methodGetHashCode
Serves as the default hash function.
(Inherited from Object.)
Protected methodGetObjectData
Returns the data needed to serialize the bag.
Public methodGetType
Gets the Type of the current instance.
(Inherited from Object.)
Public methodIndexOf
Gets the index of the first occurrence of the supplied item.
Public methodLast
Gets the maximum item in the bag per the comparer.
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 methodRemove(T)
Removes all occurrences of the supplied item from the bag.
Public methodRemove(T, Int32)
Removes a supplied number of occurrences of the supplied item from the bag.
Public methodRemoveAll
Removes all items in the supplied collection from the bag.
Public methodRemoveAt
Removes the element at the supplied index from the bag.
Public methodRemoveRange
Removes an index range of items from the bag.
Public methodRemoveWhere
Removes all elements that match the condition defined by the supplied predicate from the bag.
Public methodCode exampleRetainAll
Removes any elements that are not in the supplied collection from the bag.
Public methodReverse
Returns an IEnumerable that iterates thru the bag in reverse sort order.
Public methodCode exampleSkip
Bypasses a supplied number of items and yields the remaining items.
Public methodSkipWhile(FuncT, Boolean)
Bypasses items as long as a supplied condition is true and yields the remaining items.
Public methodSkipWhile(FuncT, Int32, Boolean)
Bypasses elements as long as a supplied index-based condition is true and yields the remaining items.
Public methodToString
Returns a string that represents the current object.
(Inherited from Object.)
Public methodTryGet
Gets the actual item for the supplied search item.
Public methodTryGetGreaterThan
Gets the least item greater than the supplied item.
Public methodTryGetGreaterThanOrEqual
Gets the least item greater than or equal to the supplied item.
Public methodTryGetLessThan
Gets the greatest item that is less than the supplied item.
Public methodTryGetLessThanOrEqual
Gets the greatest item that is less than or equal to the supplied item.
Top
Explicit Interface Implementations
  NameDescription
Explicit interface implementationPrivate methodICollectionTAdd
Adds an item to the bag.
Explicit interface implementationPrivate methodICollectionCopyTo
Copies the bag to a compatible array, starting at the supplied array index.
Explicit interface implementationPrivate methodIEnumerableTGetEnumerator
Returns an enumerator that iterates thru the bag.
Explicit interface implementationPrivate methodIEnumerableGetEnumerator
Returns an enumerator that iterates thru the collection.
Explicit interface implementationPrivate methodISerializableGetObjectData
Returns the data needed to serialize the set.
Explicit interface implementationPrivate propertyICollectionTIsReadOnly
Indicates that the collection is not read-only.
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 propertyICollectionSyncRoot
Gets an object that can be used to synchronize access to the collection.
Top
Remarks

This class is similar to RankedSetT but with multiple occurrences of an item allowed. Items with multiple occurrences have each occurrence stored individually. This flattened implementation prevents any loss of information that might occur if only a count of occurrences for a key were maintained.

Examples

The first program shows some basic operations of this class.

C#
using System;
using Kaos.Collections;

namespace ExampleApp
{
    class RbExample01
    {
        static void Main()
        {
            var crayons = new RankedBag<string> (StringComparer.InvariantCultureIgnoreCase)
            { "red", "yellow", "black", "BLACK" };

            crayons.Add ("blue");

            Console.WriteLine ($"There are {crayons.Count} total crayons:");
            foreach (var crayon in crayons)
                Console.WriteLine ($"  {crayon}");

            Console.WriteLine ($"\nThere are {crayons.GetDistinctCount()} distinct colors:");
            foreach (var crayon in crayons.Distinct())
                Console.WriteLine ($"  {crayon}");

            Console.WriteLine ($"\nGot 'gold' crayon? {crayons.Contains ("gold")}");

            // RetainAll respects cardinality so the oldest 'black' is removed:
            crayons.RetainAll (new string[] { "white", "grey", "Black", "red" });

            Console.WriteLine ("\nAfter RetainAll: ");
            foreach (var crayon in crayons)
                Console.WriteLine ($"  {crayon}");
        }

        /* Output:

        There are 5 total crayons:
          black
          BLACK
          blue
          red
          yellow

        There are 4 distinct colors:
          black
          blue
          red
          yellow

        Got 'gold' crayon? False

        After RetainAll:
          BLACK
          red

        */
    }
}
The next program shows using this class as a multimap. Positions of each character are stored and displayed for a given string.

C#
using System;
using Kaos.Collections;

namespace ExampleApp
{
    public class CharMap : IComparable<CharMap>
    {
        public char Ch { get; private set; }
        public int Pos { get; private set; }
        public CharMap (char ch, int pos) { Ch = ch; Pos = pos; }
        public int CompareTo (CharMap other) => Ch.CompareTo (other.Ch);
        public override string ToString() => Ch + " :: " + Pos;
    }

    class RbExample02
    {
        static void Main()
        {
            var map = new RankedBag<CharMap>();
            string s1 = "this is it";

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

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

        /* Output:

        h :: 1
        i :: 2
        i :: 5
        i :: 8
        s :: 3
        s :: 6
        t :: 0
        t :: 9

        */
    }
}

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 ExamComparer : Comparer<Exam>
    {
        public override int Compare (Exam x1, Exam x2) => x1.Score - x2.Score;
    }

    [Serializable]
    public class Exam : ISerializable
    {
        public int Score { get; private set; }
        public string Name { get; private set; }

        public Exam (int score, string name)
        { this.Score = score; this.Name = name; }

        protected Exam (SerializationInfo info, StreamingContext context)
        {
            this.Score = (int) info.GetValue ("Score", typeof (int));
            this.Name = (string) info.GetValue ("Name", typeof (string));
        }

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

        public override string ToString() => Score + ", " + Name;
    }

    class RbExample05
    {
        static void Main()
        {
            var bag1 = new RankedBag<Exam> (new ExamComparer());
            bag1.Add (new Exam (5, "Jack"));
            bag1.Add (new Exam (2, "Ned"));
            bag1.Add (new Exam (2, "Betty"));
            bag1.Add (new Exam (3, "Paul"));
            bag1.Add (new Exam (5, "John"));

            Console.WriteLine ("Items are inserted after other items that compare equally:");
            foreach (var item in bag1)
                Console.WriteLine ($"  {item}");

            string fileName = "Exams.bin";
            IFormatter formatter = new BinaryFormatter();

            SerializeExams (fileName, bag1, formatter);
            Console.WriteLine ($"\nWrote {bag1.Count} items to file '{fileName}'.");
            Console.WriteLine ();

            RankedBag<Exam> bag2 = DeserializeExams (fileName, formatter);
            Console.WriteLine ($"Read back {bag2.Count} items:");

            foreach (var p2 in bag2)
                Console.WriteLine ($"  {p2}");
        }

        static void SerializeExams (string fn, RankedBag<Exam> bag, IFormatter formatter)
        {
            using (var fs = new FileStream (fn, FileMode.Create))
            { formatter.Serialize (fs, bag); }
        }

        static RankedBag<Exam> DeserializeExams (string fn, IFormatter formatter)
        {
            using (var fs = new FileStream (fn, FileMode.Open))
            { return (RankedBag<Exam>) formatter.Deserialize (fs); }
        }

        /* Output:

        Items are inserted after other items that compare equally:
          2, Ned
          2, Betty
          3, Paul
          5, Jack
          5, John

        Wrote 5 items to file 'Exams.bin'.

        Read back 5 items:
          2, Ned
          2, Betty
          3, Paul
          5, Jack
          5, John

        */
    }
}
See Also