Merge pull request #4198 from vkargov/vk-prevbb
[mono.git] / mcs / class / Mono.C5 / C5 / Collections.cs
index e735b50cf57597653b15c746a137d6a9c3bf2a92..a4164e9ffcd007e55d71093f2c4027a5c2d484f1 100644 (file)
-#if NET_2_0
-/*\r
- Copyright (c) 2003-2006 Niels Kokholm and Peter Sestoft\r
- Permission is hereby granted, free of charge, to any person obtaining a copy\r
- of this software and associated documentation files (the "Software"), to deal\r
- in the Software without restriction, including without limitation the rights\r
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r
- copies of the Software, and to permit persons to whom the Software is\r
- furnished to do so, subject to the following conditions:\r
\r
- The above copyright notice and this permission notice shall be included in\r
- all copies or substantial portions of the Software.\r
\r
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r
- SOFTWARE.\r
-*/\r
-\r
-#define IMPROVED_COLLECTION_HASHFUNCTION\r
-\r
-using System;\r
-using System.Diagnostics;\r
-using SCG = System.Collections.Generic;\r
-namespace C5\r
-{\r
-  /// <summary>\r
-  /// A base class for implementing an IEnumerable&lt;T&gt;\r
-  /// </summary>\r
-  [Serializable]\r
-  public abstract class EnumerableBase<T> : SCG.IEnumerable<T>\r
-  {\r
-    /// <summary>\r
-    /// Create an enumerator for this collection.\r
-    /// </summary>\r
-    /// <returns>The enumerator</returns>\r
-    public abstract SCG.IEnumerator<T> GetEnumerator();\r
-\r
-    /// <summary>\r
-    /// Count the number of items in an enumerable by enumeration\r
-    /// </summary>\r
-    /// <param name="items">The enumerable to count</param>\r
-    /// <returns>The size of the enumerable</returns>\r
-    [Tested]\r
-    protected static int countItems(SCG.IEnumerable<T> items)\r
-    {\r
-      ICollectionValue<T> jtems = items as ICollectionValue<T>;\r
-\r
-      if (jtems != null)\r
-        return jtems.Count;\r
-\r
-      int count = 0;\r
-\r
-      using (SCG.IEnumerator<T> e = items.GetEnumerator())\r
-        while (e.MoveNext()) count++;\r
-\r
-      return count;\r
-    }\r
-\r
-    #region IEnumerable Members\r
-\r
-    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()\r
-    {\r
-      return GetEnumerator();\r
-    }\r
-\r
-    #endregion\r
-  }\r
-\r
-\r
-  /// <summary>\r
-  /// Base class for classes implementing ICollectionValue[T]\r
-  /// </summary>\r
-  [Serializable]\r
-  public abstract class CollectionValueBase<T> : EnumerableBase<T>, ICollectionValue<T>, IShowable\r
-  {\r
-    #region Event handling\r
-    EventBlock<T> eventBlock;\r
-    /// <summary>\r
-    /// \r
-    /// </summary>\r
-    /// <value></value>\r
-    public virtual EventTypeEnum ListenableEvents { get { return 0; } }\r
-\r
-    /// <summary>\r
-    /// A flag bitmap of the events currently subscribed to by this collection.\r
-    /// </summary>\r
-    /// <value></value>\r
-    public virtual EventTypeEnum ActiveEvents { get { return eventBlock == null ? 0 : eventBlock.events; } }\r
-\r
-    private void checkWillListen(EventTypeEnum eventType)\r
-    {\r
-      if ((ListenableEvents & eventType) == 0)\r
-        throw new UnlistenableEventException();\r
-    }\r
-\r
-    /// <summary>\r
-    /// The change event. Will be raised for every change operation on the collection.\r
-    /// </summary>\r
-    public virtual event CollectionChangedHandler<T> CollectionChanged\r
-    {\r
-      add { checkWillListen(EventTypeEnum.Changed); (eventBlock ?? (eventBlock = new EventBlock<T>())).CollectionChanged += value; }\r
-      remove\r
-      {\r
-        checkWillListen(EventTypeEnum.Changed);\r
-        if (eventBlock != null)\r
-        {\r
-          eventBlock.CollectionChanged -= value;\r
-          if (eventBlock.events == 0) eventBlock = null;\r
-        }\r
-      }\r
-    }\r
-    /// <summary>\r
-    /// Fire the CollectionChanged event\r
-    /// </summary>\r
-    protected virtual void raiseCollectionChanged()\r
-    { if (eventBlock != null) eventBlock.raiseCollectionChanged(this); }\r
-\r
-    /// <summary>\r
-    /// The clear event. Will be raised for every Clear operation on the collection.\r
-    /// </summary>\r
-    public virtual event CollectionClearedHandler<T> CollectionCleared\r
-    {\r
-      add { checkWillListen(EventTypeEnum.Cleared); (eventBlock ?? (eventBlock = new EventBlock<T>())).CollectionCleared += value; }\r
-      remove\r
-      {\r
-        checkWillListen(EventTypeEnum.Cleared);\r
-        if (eventBlock != null)\r
-        {\r
-          eventBlock.CollectionCleared -= value;\r
-          if (eventBlock.events == 0) eventBlock = null;\r
-        }\r
-      }\r
-    }\r
-    /// <summary>\r
-    /// Fire the CollectionCleared event\r
-    /// </summary>\r
-    protected virtual void raiseCollectionCleared(bool full, int count)\r
-    { if (eventBlock != null) eventBlock.raiseCollectionCleared(this, full, count); }\r
-\r
-    /// <summary>\r
-    /// Fire the CollectionCleared event\r
-    /// </summary>\r
-    protected virtual void raiseCollectionCleared(bool full, int count, int? offset)\r
-    { if (eventBlock != null) eventBlock.raiseCollectionCleared(this, full, count, offset); }\r
-\r
-    /// <summary>\r
-    /// The item added  event. Will be raised for every individual addition to the collection.\r
-    /// </summary>\r
-    public virtual event ItemsAddedHandler<T> ItemsAdded\r
-    {\r
-      add { checkWillListen(EventTypeEnum.Added); (eventBlock ?? (eventBlock = new EventBlock<T>())).ItemsAdded += value; }\r
-      remove\r
-      {\r
-        checkWillListen(EventTypeEnum.Added);\r
-        if (eventBlock != null)\r
-        {\r
-          eventBlock.ItemsAdded -= value;\r
-          if (eventBlock.events == 0) eventBlock = null;\r
-        }\r
-      }\r
-    }\r
-    /// <summary>\r
-    /// Fire the ItemsAdded event\r
-    /// </summary>\r
-    /// <param name="item">The item that was added</param>\r
-    /// <param name="count"></param>\r
-    protected virtual void raiseItemsAdded(T item, int count)\r
-    { if (eventBlock != null) eventBlock.raiseItemsAdded(this, item, count); }\r
-\r
-    /// <summary>\r
-    /// The item removed event. Will be raised for every individual removal from the collection.\r
-    /// </summary>\r
-    public virtual event ItemsRemovedHandler<T> ItemsRemoved\r
-    {\r
-      add { checkWillListen(EventTypeEnum.Removed); (eventBlock ?? (eventBlock = new EventBlock<T>())).ItemsRemoved += value; }\r
-      remove\r
-      {\r
-        checkWillListen(EventTypeEnum.Removed);\r
-        if (eventBlock != null)\r
-        {\r
-          eventBlock.ItemsRemoved -= value;\r
-          if (eventBlock.events == 0) eventBlock = null;\r
-        }\r
-      }\r
-    }\r
-    /// <summary>\r
-    /// Fire the ItemsRemoved event\r
-    /// </summary>\r
-    /// <param name="item">The item that was removed</param>\r
-    /// <param name="count"></param>\r
-    protected virtual void raiseItemsRemoved(T item, int count)\r
-    { if (eventBlock != null) eventBlock.raiseItemsRemoved(this, item, count); }\r
-\r
-    /// <summary>\r
-    /// The item added  event. Will be raised for every individual addition to the collection.\r
-    /// </summary>\r
-    public virtual event ItemInsertedHandler<T> ItemInserted\r
-    {\r
-      add { checkWillListen(EventTypeEnum.Inserted); (eventBlock ?? (eventBlock = new EventBlock<T>())).ItemInserted += value; }\r
-      remove\r
-      {\r
-        checkWillListen(EventTypeEnum.Inserted);\r
-        if (eventBlock != null)\r
-        {\r
-          eventBlock.ItemInserted -= value;\r
-          if (eventBlock.events == 0) eventBlock = null;\r
-        }\r
-      }\r
-    }\r
-    /// <summary>\r
-    /// Fire the ItemInserted event\r
-    /// </summary>\r
-    /// <param name="item">The item that was added</param>\r
-    /// <param name="index"></param>\r
-    protected virtual void raiseItemInserted(T item, int index)\r
-    { if (eventBlock != null) eventBlock.raiseItemInserted(this, item, index); }\r
-\r
-    /// <summary>\r
-    /// The item removed event. Will be raised for every individual removal from the collection.\r
-    /// </summary>\r
-    public virtual event ItemRemovedAtHandler<T> ItemRemovedAt\r
-    {\r
-      add { checkWillListen(EventTypeEnum.RemovedAt); (eventBlock ?? (eventBlock = new EventBlock<T>())).ItemRemovedAt += value; }\r
-      remove\r
-      {\r
-        checkWillListen(EventTypeEnum.RemovedAt);\r
-        if (eventBlock != null)\r
-        {\r
-          eventBlock.ItemRemovedAt -= value;\r
-          if (eventBlock.events == 0) eventBlock = null;\r
-        }\r
-      }\r
-    }\r
-    /// <summary> \r
-    /// Fire the ItemRemovedAt event\r
-    /// </summary>\r
-    /// <param name="item">The item that was removed</param>\r
-    /// <param name="index"></param>\r
-    protected virtual void raiseItemRemovedAt(T item, int index)\r
-    { if (eventBlock != null) eventBlock.raiseItemRemovedAt(this, item, index); }\r
-\r
-    #region Event support for IList\r
-    /// <summary>\r
-    /// \r
-    /// </summary>\r
-    /// <param name="index"></param>\r
-    /// <param name="value"></param>\r
-    /// <param name="item"></param>\r
-    protected virtual void raiseForSetThis(int index, T value, T item)\r
-    {\r
-      if (ActiveEvents != 0)\r
-      {\r
-        raiseItemsRemoved(item, 1);\r
-        raiseItemRemovedAt(item, index);\r
-        raiseItemsAdded(value, 1);\r
-        raiseItemInserted(value, index);\r
-        raiseCollectionChanged();\r
-      }\r
-    }\r
-    /// <summary>\r
-    /// \r
-    /// </summary>\r
-    /// <param name="i"></param>\r
-    /// <param name="item"></param>\r
-    protected virtual void raiseForInsert(int i, T item)\r
-    {\r
-      if (ActiveEvents != 0)\r
-      {\r
-        raiseItemInserted(item, i);\r
-        raiseItemsAdded(item, 1);\r
-        raiseCollectionChanged();\r
-      }\r
-    }\r
-\r
-    /// <summary>\r
-    /// \r
-    /// </summary>\r
-    /// <param name="item"></param>\r
-    protected void raiseForRemove(T item)\r
-    {\r
-      if (ActiveEvents != 0)\r
-      {\r
-        raiseItemsRemoved(item, 1);\r
-        raiseCollectionChanged();\r
-      }\r
-    }\r
-\r
-    /// <summary>\r
-    /// \r
-    /// </summary>\r
-    /// <param name="item"></param>\r
-    /// <param name="count"></param>\r
-    protected void raiseForRemove(T item, int count)\r
-    {\r
-      if (ActiveEvents != 0)\r
-      {\r
-        raiseItemsRemoved(item, count);\r
-        raiseCollectionChanged();\r
-      }\r
-    }\r
-\r
-    /// <summary>\r
-    /// \r
-    /// </summary>\r
-    /// <param name="index"></param>\r
-    /// <param name="item"></param>\r
-    protected void raiseForRemoveAt(int index, T item)\r
-    {\r
-      if (ActiveEvents != 0)\r
-      {\r
-        raiseItemRemovedAt(item, index);\r
-        raiseItemsRemoved(item, 1);\r
-        raiseCollectionChanged();\r
-      }\r
-    }\r
-\r
-    #endregion\r
-\r
-    #region Event  Support for ICollection\r
-    /// <summary>\r
-    /// \r
-    /// </summary>\r
-    /// <param name="newitem"></param>\r
-    /// <param name="olditem"></param>\r
-    protected virtual void raiseForUpdate(T newitem, T olditem)\r
-    {\r
-      if (ActiveEvents != 0)\r
-      {\r
-        raiseItemsRemoved(olditem, 1);\r
-        raiseItemsAdded(newitem, 1);\r
-        raiseCollectionChanged();\r
-      }\r
-    }\r
-    /// <summary>\r
-    /// \r
-    /// </summary>\r
-    /// <param name="newitem"></param>\r
-    /// <param name="olditem"></param>\r
-    /// <param name="count"></param>\r
-    protected virtual void raiseForUpdate(T newitem, T olditem, int count)\r
-    {\r
-      if (ActiveEvents != 0)\r
-      {\r
-        raiseItemsRemoved(olditem, count);\r
-        raiseItemsAdded(newitem, count);\r
-        raiseCollectionChanged();\r
-      }\r
-    }\r
-    /// <summary>\r
-    /// \r
-    /// </summary>\r
-    /// <param name="item"></param>\r
-    protected virtual void raiseForAdd(T item)\r
-    {\r
-      if (ActiveEvents != 0)\r
-      {\r
-        raiseItemsAdded(item, 1);\r
-        raiseCollectionChanged();\r
-      }\r
-    }\r
-    /// <summary>\r
-    /// \r
-    /// </summary>\r
-    /// <param name="wasRemoved"></param>\r
-    protected virtual void raiseForRemoveAll(ICollectionValue<T> wasRemoved)\r
-    {\r
-      if ((ActiveEvents & EventTypeEnum.Removed) != 0)\r
-        foreach (T item in wasRemoved)\r
-          raiseItemsRemoved(item, 1);\r
-      if (wasRemoved != null && wasRemoved.Count > 0)\r
-        raiseCollectionChanged();\r
-    }\r
-\r
-    /// <summary>\r
-    /// \r
-    /// </summary>\r
-    protected class RaiseForRemoveAllHandler\r
-    {\r
-      CollectionValueBase<T> collection;\r
-      CircularQueue<T> wasRemoved;\r
-      bool wasChanged = false;\r
-\r
-      /// <summary>\r
-      /// \r
-      /// </summary>\r
-      /// <param name="collection"></param>\r
-      public RaiseForRemoveAllHandler(CollectionValueBase<T> collection)\r
-      {\r
-        this.collection = collection;\r
-        mustFireRemoved = (collection.ActiveEvents & EventTypeEnum.Removed) != 0;\r
-        MustFire = (collection.ActiveEvents & (EventTypeEnum.Removed | EventTypeEnum.Changed)) != 0;\r
-      }\r
-\r
-      bool mustFireRemoved;\r
-      /// <summary>\r
-      /// \r
-      /// </summary>\r
-      public readonly bool MustFire;\r
-\r
-      /// <summary>\r
-      /// \r
-      /// </summary>\r
-      /// <param name="item"></param>\r
-      public void Remove(T item)\r
-      {\r
-        if (mustFireRemoved)\r
-        {\r
-          if (wasRemoved == null)\r
-            wasRemoved = new CircularQueue<T>();\r
-          wasRemoved.Enqueue(item);\r
-        }\r
-        if (!wasChanged)\r
-          wasChanged = true;\r
-      }\r
-\r
-      /// <summary>\r
-      /// \r
-      /// </summary>\r
-      public void Raise()\r
-      {\r
-        if (wasRemoved != null)\r
-          foreach (T item in wasRemoved)\r
-            collection.raiseItemsRemoved(item, 1);\r
-        if (wasChanged)\r
-          collection.raiseCollectionChanged();\r
-      }\r
-    }\r
-    #endregion\r
-\r
-    #endregion\r
-\r
-    /// <summary>\r
-    /// Check if collection is empty.\r
-    /// </summary>\r
-    /// <value>True if empty</value>\r
-    public abstract bool IsEmpty { get;}\r
-\r
-    /// <summary>\r
-    /// The number of items in this collection.\r
-    /// </summary>\r
-    /// <value></value>\r
-    public abstract int Count { get;}\r
-\r
-    /// <summary>\r
-    /// The value is symbolic indicating the type of asymptotic complexity\r
-    /// in terms of the size of this collection (worst-case or amortized as\r
-    /// relevant).\r
-    /// </summary>\r
-    /// <value>A characterization of the speed of the \r
-    /// <code>Count</code> property in this collection.</value>\r
-    public abstract Speed CountSpeed { get; }\r
-\r
-    /// <summary>\r
-    /// Copy the items of this collection to part of an array.\r
-    /// </summary>\r
-    /// <exception cref="ArgumentOutOfRangeException"> if <code>index</code> \r
-    /// is not a valid index\r
-    /// into the array (i.e. negative or not less than the size of the array)\r
-    /// or the array does not have room for the items.</exception>\r
-    /// <param name="array">The array to copy to.</param>\r
-    /// <param name="index">The starting index.</param>\r
-    [Tested]\r
-    public virtual void CopyTo(T[] array, int index)\r
-    {\r
-#warning This code does not fit the doc comment and unit tests\r
-      if (index < 0 || index + Count > array.Length)\r
-        throw new ArgumentOutOfRangeException();\r
-\r
-      foreach (T item in this) array[index++] = item;\r
-    }\r
-\r
-    /// <summary>\r
-    /// Create an array with the items of this collection (in the same order as an\r
-    /// enumerator would output them).\r
-    /// </summary>\r
-    /// <returns>The array</returns>\r
-    //[Tested]\r
-    public virtual T[] ToArray()\r
-    {\r
-      T[] res = new T[Count];\r
-      int i = 0;\r
-\r
-      foreach (T item in this) res[i++] = item;\r
-\r
-      return res;\r
-    }\r
-\r
-    /// <summary>\r
-    /// Apply an single argument action, <see cref="T:C5.Act`1"/> to this enumerable\r
-    /// </summary>\r
-    /// <param name="action">The action delegate</param>\r
-    [Tested]\r
-    public virtual void Apply(Act<T> action)\r
-    {\r
-      foreach (T item in this)\r
-        action(item);\r
-    }\r
-\r
-\r
-    /// <summary>\r
-    /// Check if there exists an item  that satisfies a\r
-    /// specific predicate in this collection.\r
-    /// </summary>\r
-    /// <param name="predicate">A delegate \r
-    /// (<see cref="T:C5.Fun`2"/> with <code>R = bool</code>) \r
-    /// defining the predicate</param>\r
-    /// <returns>True if such an item exists</returns>\r
-    [Tested]\r
-    public virtual bool Exists(Fun<T, bool> predicate)\r
-    {\r
-      foreach (T item in this)\r
-        if (predicate(item))\r
-          return true;\r
-\r
-      return false;\r
-    }\r
-\r
-    /// <summary>\r
-    /// Check if there exists an item  that satisfies a\r
-    /// specific predicate in this collection and return the first one in enumeration order.\r
-    /// </summary>\r
-    /// <param name="predicate">A delegate \r
-    /// (<see cref="T:C5.Fun`2"/> with <code>R == bool</code>) defining the predicate</param>\r
-    /// <param name="item"></param>\r
-    /// <returns>True is such an item exists</returns>\r
-    public virtual bool Find(Fun<T, bool> predicate, out T item)\r
-    {\r
-      foreach (T jtem in this)\r
-        if (predicate(jtem))\r
-        {\r
-          item = jtem;\r
-          return true;\r
-        }\r
-      item = default(T);\r
-      return false;\r
-    }\r
-\r
-    /// <summary>\r
-    /// Check if all items in this collection satisfies a specific predicate.\r
-    /// </summary>\r
-    /// <param name="predicate">A delegate \r
-    /// (<see cref="T:C5.Fun`2"/> with <code>R = bool</code>) \r
-    /// defining the predicate</param>\r
-    /// <returns>True if all items satisfies the predicate</returns>\r
-    [Tested]\r
-    public virtual bool All(Fun<T, bool> predicate)\r
-    {\r
-      foreach (T item in this)\r
-        if (!predicate(item))\r
-          return false;\r
-\r
-      return true;\r
-    }\r
-\r
-    /// <summary>\r
-    /// Create an enumerable, enumerating the items of this collection that satisfies \r
-    /// a certain condition.\r
-    /// </summary>\r
-    /// <param name="predicate">A delegate \r
-    /// (<see cref="T:C5.Fun`2"/> with <code>R = bool</code>) \r
-    /// defining the predicate</param>\r
-    /// <returns>The filtered enumerable</returns>\r
-    public virtual SCG.IEnumerable<T> Filter(Fun<T, bool> predicate)\r
-    {\r
-      foreach (T item in this)\r
-        if (predicate(item))\r
-          yield return item;\r
-    }\r
-\r
-    /// <summary>\r
-    /// Choose some item of this collection. \r
-    /// </summary>\r
-    /// <exception cref="NoSuchItemException">if collection is empty.</exception>\r
-    /// <returns></returns>\r
-    public abstract T Choose();\r
-\r
-\r
-    /// <summary>\r
-    /// Create an enumerator for this collection.\r
-    /// </summary>\r
-    /// <returns>The enumerator</returns>\r
-    public override abstract SCG.IEnumerator<T> GetEnumerator();\r
-\r
-    #region IShowable Members\r
-\r
-    /// <summary>\r
-    /// \r
-    /// </summary>\r
-    /// <param name="stringbuilder"></param>\r
-    /// <param name="rest"></param>\r
-    /// <param name="formatProvider"></param>\r
-    /// <returns></returns>\r
-    public virtual bool Show(System.Text.StringBuilder stringbuilder, ref int rest, IFormatProvider formatProvider)\r
-    {\r
-      return Showing.ShowCollectionValue<T>(this, stringbuilder, ref rest, formatProvider);\r
-    }\r
-    #endregion\r
-\r
-    #region IFormattable Members\r
-\r
-    /// <summary>\r
-    /// \r
-    /// </summary>\r
-    /// <param name="format"></param>\r
-    /// <param name="formatProvider"></param>\r
-    /// <returns></returns>\r
-    public virtual string ToString(string format, IFormatProvider formatProvider)\r
-    {\r
-      return Showing.ShowString(this, format, formatProvider);\r
-    }\r
-\r
-    #endregion\r
-\r
-    /// <summary>\r
-    /// \r
-    /// </summary>\r
-    /// <returns></returns>\r
-    public override string ToString()\r
-    {\r
-      return ToString(null, null);\r
-    }\r
-\r
-  }\r
-\r
-  /// <summary>\r
-  /// \r
-  /// </summary>\r
-  /// <typeparam name="T"></typeparam>\r
-  public abstract class DirectedCollectionValueBase<T> : CollectionValueBase<T>, IDirectedCollectionValue<T>\r
-  {\r
-    /// <summary>\r
-    /// <code>Forwards</code> if same, else <code>Backwards</code>\r
-    /// </summary>\r
-    /// <value>The enumeration direction relative to the original collection.</value>\r
-    public virtual EnumerationDirection Direction { [Tested]get { return EnumerationDirection.Forwards; } }\r
-\r
-    /// <summary>\r
-    /// \r
-    /// </summary>\r
-    /// <returns></returns>\r
-    public abstract IDirectedCollectionValue<T> Backwards();\r
-\r
-    IDirectedEnumerable<T> IDirectedEnumerable<T>.Backwards() { return this.Backwards(); }\r
-\r
-    /// <summary>\r
-    /// Check if there exists an item  that satisfies a\r
-    /// specific predicate in this collection and return the first one in enumeration order.\r
-    /// </summary>\r
-    /// <param name="predicate">A delegate \r
-    /// (<see cref="T:C5.Fun`2"/> with <code>R == bool</code>) defining the predicate</param>\r
-    /// <param name="item"></param>\r
-    /// <returns>True is such an item exists</returns>\r
-    public virtual bool FindLast(Fun<T, bool> predicate, out T item)\r
-    {\r
-      foreach (T jtem in Backwards())\r
-        if (predicate(jtem))\r
-        {\r
-          item = jtem;\r
-          return true;\r
-        }\r
-      item = default(T);\r
-      return false;\r
-    }\r
-  }\r
-\r
-  /// <summary>\r
-  /// Base class (abstract) for ICollection implementations.\r
-  /// </summary>\r
-  [Serializable]\r
-  public abstract class CollectionBase<T> : CollectionValueBase<T>\r
-  {\r
-    #region Fields\r
-\r
-    object syncroot = new object();\r
-\r
-    /// <summary>\r
-    /// The underlying field of the ReadOnly property\r
-    /// </summary>\r
-    protected bool isReadOnly = false;\r
-\r
-    /// <summary>\r
-    /// The current stamp value\r
-    /// </summary>\r
-    protected int stamp;\r
-\r
-    /// <summary>\r
-    /// The number of items in the collection\r
-    /// </summary>\r
-    protected int size;\r
-\r
-    /// <summary>\r
-    /// The item equalityComparer of the collection\r
-    /// </summary>\r
-    protected readonly SCG.IEqualityComparer<T> itemequalityComparer;\r
-\r
-    int iUnSequencedHashCode, iUnSequencedHashCodeStamp = -1;\r
-\r
-    #endregion\r
-\r
-    /// <summary>\r
-    /// \r
-    /// </summary>\r
-    /// <param name="itemequalityComparer"></param>\r
-    public CollectionBase(SCG.IEqualityComparer<T> itemequalityComparer)\r
-    {\r
-      if (itemequalityComparer == null)\r
-        throw new NullReferenceException("Item EqualityComparer cannot be null.");\r
-      this.itemequalityComparer = itemequalityComparer;\r
-    }\r
-\r
-    #region Util\r
-\r
-    /// <summary>\r
-    /// Utility method for range checking.\r
-    /// </summary>\r
-    /// <exception cref="ArgumentOutOfRangeException"> if the start or count is negative or\r
-    ///  if the range does not fit within collection size.</exception>\r
-    /// <param name="start">start of range</param>\r
-    /// <param name="count">size of range</param>\r
-    [Tested]\r
-    protected void checkRange(int start, int count)\r
-    {\r
-      if (start < 0 || count < 0 || start + count > size)\r
-        throw new ArgumentOutOfRangeException();\r
-    }\r
-\r
-\r
-    /// <summary>\r
-    /// Compute the unsequenced hash code of a collection\r
-    /// </summary>\r
-    /// <param name="items">The collection to compute hash code for</param>\r
-    /// <param name="itemequalityComparer">The item equalityComparer</param>\r
-    /// <returns>The hash code</returns>\r
-    [Tested]\r
-    public static int ComputeHashCode(ICollectionValue<T> items, SCG.IEqualityComparer<T> itemequalityComparer)\r
-    {\r
-      int h = 0;\r
-\r
-#if IMPROVED_COLLECTION_HASHFUNCTION\r
-      //But still heuristic: \r
-      //Note: the three odd factors should really be random, \r
-      //but there will be a problem with serialization/deserialization!\r
-      //Two products is too few\r
-      foreach (T item in items)\r
-      {\r
-        uint h1 = (uint)itemequalityComparer.GetHashCode(item);\r
-\r
-        h += (int)((h1 * 1529784657 + 1) ^ (h1 * 2912831877) ^ (h1 * 1118771817 + 2));\r
-      }\r
-\r
-      return h;\r
-      /*\r
-            The pairs (-1657792980, -1570288808) and (1862883298, -272461342) gives the same\r
-            unsequenced hashcode with this hashfunction. The pair was found with code like\r
-\r
-            HashDictionary<int, int[]> set = new HashDictionary<int, int[]>();\r
-            Random rnd = new C5Random(12345);\r
-            while (true)\r
-            {\r
-                int[] a = new int[2];\r
-                a[0] = rnd.Next(); a[1] = rnd.Next();\r
-                int h = unsequencedhashcode(a);\r
-                int[] b = a;\r
-                if (set.FindOrAdd(h, ref b))\r
-                {\r
-                    Console.WriteLine("Code {5}, Pair ({1},{2}) number {0} matched other pair ({3},{4})", set.Count, a[0], a[1], b[0], b[1], h);\r
-                }\r
-            }\r
-            */\r
-#else\r
-            foreach (T item in items)\r
-                               h ^= itemequalityComparer.GetHashCode(item);\r
-\r
-                       return (items.Count << 16) + h;\r
-#endif\r
-    }\r
-\r
-    static Type isortedtype = typeof(ISorted<T>);\r
-\r
-    /// <summary>\r
-    /// Examine if tit and tat are equal as unsequenced collections\r
-    /// using the specified item equalityComparer (assumed compatible with the two collections).\r
-    /// </summary>\r
-    /// <param name="collection1">The first collection</param>\r
-    /// <param name="collection2">The second collection</param>\r
-    /// <param name="itemequalityComparer">The item equalityComparer to use for comparison</param>\r
-    /// <returns>True if equal</returns>\r
-    [Tested]\r
-    public static bool StaticEquals(ICollection<T> collection1, ICollection<T> collection2, SCG.IEqualityComparer<T> itemequalityComparer)\r
-    {\r
-      if (object.ReferenceEquals(collection1, collection2))\r
-        return true;\r
-\r
-      if (collection1.Count != collection2.Count)\r
-        return false;\r
-\r
-      //This way we might run through both enumerations twice, but\r
-      //probably not (if the hash codes are good)\r
-      //TODO: cehck equal equalityComparers, at least here!\r
-      if (collection1.GetUnsequencedHashCode() != collection2.GetUnsequencedHashCode())\r
-        return false;\r
-\r
-      //TODO: move this to the sorted implementation classes? \r
-      //Really depends on speed of IntanceOfType: we could save a cast\r
-      {\r
-        ISorted<T> stit, stat;\r
-        if ((stit = collection1 as ISorted<T>) != null && (stat = collection2 as ISorted<T>) != null && stit.Comparer == stat.Comparer)\r
-        {\r
-          using (SCG.IEnumerator<T> dat = collection2.GetEnumerator(), dit = collection1.GetEnumerator())\r
-          {\r
-            while (dit.MoveNext())\r
-            {\r
-              dat.MoveNext();\r
-              if (!itemequalityComparer.Equals(dit.Current, dat.Current))\r
-                return false;\r
-            }\r
-            return true;\r
-          }\r
-        }\r
-      }\r
-\r
-      if (!collection1.AllowsDuplicates && (collection2.AllowsDuplicates || collection2.ContainsSpeed >= collection1.ContainsSpeed))\r
-      {\r
-        foreach (T x in collection1) if (!collection2.Contains(x)) return false;\r
-      }\r
-      else if (!collection2.AllowsDuplicates)\r
-      {\r
-        foreach (T x in collection2) if (!collection1.Contains(x)) return false;\r
-      }\r
-      // Now tit.AllowsDuplicates && tat.AllowsDuplicates\r
-      else if (collection1.DuplicatesByCounting && collection2.DuplicatesByCounting)\r
-      {\r
-        foreach (T item in collection2) if (collection1.ContainsCount(item) != collection2.ContainsCount(item)) return false;\r
-      }\r
-      else\r
-      {\r
-        //To avoid an O(n^2) algorithm, we make an aux hashtable to hold the count of items\r
-        HashDictionary<T, int> dict = new HashDictionary<T, int>();\r
-        foreach (T item in collection2)\r
-        {\r
-          int count = 1;\r
-          if (dict.FindOrAdd(item, ref count))\r
-            dict[item] = count + 1;\r
-        }\r
-        foreach (T item in collection1)\r
-        {\r
-          int count;\r
-          if (dict.Find(item, out count) && count > 0)\r
-            dict[item] = count - 1;\r
-          else\r
-            return false;\r
-        }\r
-        return true;\r
-      }\r
-\r
-      return true;\r
-    }\r
-\r
-\r
-    /// <summary>\r
-    /// Get the unsequenced collection hash code of this collection: from the cached \r
-    /// value if present and up to date, else (re)compute.\r
-    /// </summary>\r
-    /// <returns>The hash code</returns>\r
-    public virtual int GetUnsequencedHashCode()\r
-    {\r
-      if (iUnSequencedHashCodeStamp == stamp)\r
-        return iUnSequencedHashCode;\r
-\r
-      iUnSequencedHashCode = ComputeHashCode(this, itemequalityComparer);\r
-      iUnSequencedHashCodeStamp = stamp;\r
-      return iUnSequencedHashCode;\r
-    }\r
-\r
-\r
-    /// <summary>\r
-    /// Check if the contents of that is equal to the contents of this\r
-    /// in the unsequenced sense. Using the item equalityComparer of this collection. \r
-    /// Assuming that the item EqualityComparer is compatible with otherCollection!\r
-    /// </summary>\r
-    /// <param name="otherCollection">The collection to compare to.</param>\r
-    /// <returns>True if  equal</returns>\r
-    public virtual bool UnsequencedEquals(ICollection<T> otherCollection)\r
-    {\r
-      return otherCollection != null && StaticEquals((ICollection<T>)this, otherCollection, itemequalityComparer);\r
-    }\r
-\r
-\r
-    /// <summary>\r
-    /// Check if the collection has been modified since a specified time, expressed as a stamp value.\r
-    /// </summary>\r
-    /// <exception cref="CollectionModifiedException"> if this collection has been updated \r
-    /// since a target time</exception>\r
-    /// <param name="thestamp">The stamp identifying the target time</param>\r
-    protected virtual void modifycheck(int thestamp)\r
-    {\r
-      if (this.stamp != thestamp)\r
-        throw new CollectionModifiedException();\r
-    }\r
-\r
-\r
-    /// <summary>\r
-    /// Check if it is valid to perform update operations, and if so increment stamp.\r
-    /// </summary>\r
-    /// <exception cref="ReadOnlyCollectionException">If colection is read-only</exception>\r
-    protected virtual void updatecheck()\r
-    {\r
-      if (isReadOnly)\r
-        throw new ReadOnlyCollectionException();\r
-\r
-      stamp++;\r
-    }\r
-\r
-    #endregion\r
-\r
-    #region ICollection<T> members\r
-\r
-    /// <summary>\r
-    /// \r
-    /// </summary>\r
-    /// <value>True if this collection is read only</value>\r
-    [Tested]\r
-    public virtual bool IsReadOnly { [Tested]get { return isReadOnly; } }\r
-\r
-    #endregion\r
-\r
-    #region ICollectionValue<T> members\r
-    /// <summary>\r
-    /// \r
-    /// </summary>\r
-    /// <value>The size of this collection</value>\r
-    [Tested]\r
-    public override int Count { [Tested]get { return size; } }\r
-\r
-    /// <summary>\r
-    /// The value is symbolic indicating the type of asymptotic complexity\r
-    /// in terms of the size of this collection (worst-case or amortized as\r
-    /// relevant).\r
-    /// </summary>\r
-    /// <value>A characterization of the speed of the \r
-    /// <code>Count</code> property in this collection.</value>\r
-    public override Speed CountSpeed { get { return Speed.Constant; } }\r
-\r
-\r
-    #endregion\r
-\r
-    #region IExtensible<T> members\r
-\r
-    /// <summary>\r
-    /// \r
-    /// </summary>\r
-    /// <value></value>\r
-    public virtual SCG.IEqualityComparer<T> EqualityComparer { get { return itemequalityComparer; } }\r
-\r
-    /// <summary>\r
-    /// \r
-    /// </summary>\r
-    /// <value>A distinguished object to use for locking to synchronize multithreaded access</value>\r
-    [Tested]\r
-    public virtual object SyncRoot { get { return syncroot; } }\r
-\r
-\r
-    /// <summary>\r
-    /// \r
-    /// </summary>\r
-    /// <value>True if this collection is empty</value>\r
-    [Tested]\r
-    public override bool IsEmpty { [Tested]get { return size == 0; } }\r
-\r
-    #endregion\r
-\r
-    #region IEnumerable<T> Members\r
-    /// <summary>\r
-    /// Create an enumerator for this collection.\r
-    /// </summary>\r
-    /// <returns>The enumerator</returns>\r
-    public override abstract SCG.IEnumerator<T> GetEnumerator();\r
-    #endregion\r
-  }\r
-\r
-  /// <summary>\r
-  /// \r
-  /// </summary>\r
-  /// <typeparam name="T"></typeparam>\r
-  [Serializable]\r
-  public abstract class DirectedCollectionBase<T> : CollectionBase<T>, IDirectedCollectionValue<T>\r
-  {\r
-    /// <summary>\r
-    /// \r
-    /// </summary>\r
-    /// <param name="itemequalityComparer"></param>\r
-    public DirectedCollectionBase(SCG.IEqualityComparer<T> itemequalityComparer) : base(itemequalityComparer) { }\r
-    /// <summary>\r
-    /// <code>Forwards</code> if same, else <code>Backwards</code>\r
-    /// </summary>\r
-    /// <value>The enumeration direction relative to the original collection.</value>\r
-    public virtual EnumerationDirection Direction { [Tested]get { return EnumerationDirection.Forwards; } }\r
-\r
-    /// <summary>\r
-    /// \r
-    /// </summary>\r
-    /// <returns></returns>\r
-    public abstract IDirectedCollectionValue<T> Backwards();\r
-\r
-    IDirectedEnumerable<T> IDirectedEnumerable<T>.Backwards() { return this.Backwards(); }\r
-\r
-    /// <summary>\r
-    /// Check if there exists an item  that satisfies a\r
-    /// specific predicate in this collection and return the first one in enumeration order.\r
-    /// </summary>\r
-    /// <param name="predicate">A delegate \r
-    /// (<see cref="T:C5.Fun`2"/> with <code>R == bool</code>) defining the predicate</param>\r
-    /// <param name="item"></param>\r
-    /// <returns>True is such an item exists</returns>\r
-    public virtual bool FindLast(Fun<T, bool> predicate, out T item)\r
-    {\r
-      foreach (T jtem in Backwards())\r
-        if (predicate(jtem))\r
-        {\r
-          item = jtem;\r
-          return true;\r
-        }\r
-      item = default(T);\r
-      return false;\r
-    }\r
-  }\r
-\r
-  /// <summary>\r
-  /// Base class (abstract) for sequenced collection implementations.\r
-  /// </summary>\r
-  [Serializable]\r
-  public abstract class SequencedBase<T> : DirectedCollectionBase<T>, IDirectedCollectionValue<T>\r
-  {\r
-    #region Fields\r
-\r
-    int iSequencedHashCode, iSequencedHashCodeStamp = -1;\r
-\r
-    #endregion\r
-\r
-    /// <summary>\r
-    /// \r
-    /// </summary>\r
-    /// <param name="itemequalityComparer"></param>\r
-    public SequencedBase(SCG.IEqualityComparer<T> itemequalityComparer) : base(itemequalityComparer) { }\r
-\r
-    #region Util\r
-\r
-    //TODO: make random for release\r
-    const int HASHFACTOR = 31;\r
-\r
-    /// <summary>\r
-    /// Compute the unsequenced hash code of a collection\r
-    /// </summary>\r
-    /// <param name="items">The collection to compute hash code for</param>\r
-    /// <param name="itemequalityComparer">The item equalityComparer</param>\r
-    /// <returns>The hash code</returns>\r
-    [Tested]\r
-    public static int ComputeHashCode(ISequenced<T> items, SCG.IEqualityComparer<T> itemequalityComparer)\r
-    {\r
-      //NOTE: It must be possible to devise a much stronger combined hashcode, \r
-      //but unfortunately, it has to be universal. OR we could use a (strong)\r
-      //family and initialise its parameter randomly at load time of this class!\r
-      //(We would not want to have yet a flag to check for invalidation?!)\r
-      //NBNBNB: the current hashcode has the very bad property that items with hashcode 0\r
-      // is ignored.\r
-      int iIndexedHashCode = 0;\r
-\r
-      foreach (T item in items)\r
-        iIndexedHashCode = iIndexedHashCode * HASHFACTOR + itemequalityComparer.GetHashCode(item);\r
-\r
-      return iIndexedHashCode;\r
-    }\r
-\r
-\r
-    /// <summary>\r
-    /// Examine if tit and tat are equal as sequenced collections\r
-    /// using the specified item equalityComparer (assumed compatible with the two collections).\r
-    /// </summary>\r
-    /// <param name="collection1">The first collection</param>\r
-    /// <param name="collection2">The second collection</param>\r
-    /// <param name="itemequalityComparer">The item equalityComparer to use for comparison</param>\r
-    /// <returns>True if equal</returns>\r
-    [Tested]\r
-    public static bool StaticEquals(ISequenced<T> collection1, ISequenced<T> collection2, SCG.IEqualityComparer<T> itemequalityComparer)\r
-    {\r
-      if (object.ReferenceEquals(collection1, collection2))\r
-        return true;\r
-\r
-      if (collection1.Count != collection2.Count)\r
-        return false;\r
-\r
-      //This way we might run through both enumerations twice, but\r
-      //probably not (if the hash codes are good)\r
-      if (collection1.GetSequencedHashCode() != collection2.GetSequencedHashCode())\r
-        return false;\r
-\r
-      using (SCG.IEnumerator<T> dat = collection2.GetEnumerator(), dit = collection1.GetEnumerator())\r
-      {\r
-        while (dit.MoveNext())\r
-        {\r
-          dat.MoveNext();\r
-          if (!itemequalityComparer.Equals(dit.Current, dat.Current))\r
-            return false;\r
-        }\r
-      }\r
-\r
-      return true;\r
-    }\r
-\r
-\r
-    /// <summary>\r
-    /// Get the sequenced collection hash code of this collection: from the cached \r
-    /// value if present and up to date, else (re)compute.\r
-    /// </summary>\r
-    /// <returns>The hash code</returns>\r
-    public virtual int GetSequencedHashCode()\r
-    {\r
-      if (iSequencedHashCodeStamp == stamp)\r
-        return iSequencedHashCode;\r
-\r
-      iSequencedHashCode = ComputeHashCode((ISequenced<T>)this, itemequalityComparer);\r
-      iSequencedHashCodeStamp = stamp;\r
-      return iSequencedHashCode;\r
-    }\r
-\r
-\r
-    /// <summary>\r
-    /// Check if the contents of that is equal to the contents of this\r
-    /// in the sequenced sense. Using the item equalityComparer of this collection.\r
-    /// </summary>\r
-    /// <param name="otherCollection">The collection to compare to.</param>\r
-    /// <returns>True if  equal</returns>\r
-    public virtual bool SequencedEquals(ISequenced<T> otherCollection)\r
-    {\r
-      return StaticEquals((ISequenced<T>)this, otherCollection, itemequalityComparer);\r
-    }\r
-\r
-\r
-    #endregion\r
-\r
-    /// <summary>\r
-    /// Create an enumerator for this collection.\r
-    /// </summary>\r
-    /// <returns>The enumerator</returns>\r
-    public override abstract SCG.IEnumerator<T> GetEnumerator();\r
-\r
-    /// <summary>\r
-    /// <code>Forwards</code> if same, else <code>Backwards</code>\r
-    /// </summary>\r
-    /// <value>The enumeration direction relative to the original collection.</value>\r
-    [Tested]\r
-    public override EnumerationDirection Direction { [Tested]get { return EnumerationDirection.Forwards; } }\r
-\r
-    /// <summary>\r
-    /// Check if there exists an item  that satisfies a\r
-    /// specific predicate in this collection and return the index of the first one.\r
-    /// </summary>\r
-    /// <param name="predicate">A delegate \r
-    /// (<see cref="T:C5.Fun`2"/> with <code>R == bool</code>) defining the predicate</param>\r
-    /// <returns>the index, if found, a negative value else</returns>\r
-    public int FindIndex(Fun<T, bool> predicate)\r
-    {\r
-      int index = 0;\r
-      foreach (T item in this)\r
-      {\r
-        if (predicate(item))\r
-          return index;\r
-        index++;\r
-      }\r
-      return -1;\r
-    }\r
-\r
-    /// <summary>\r
-    /// Check if there exists an item  that satisfies a\r
-    /// specific predicate in this collection and return the index of the last one.\r
-    /// </summary>\r
-    /// <param name="predicate">A delegate \r
-    /// (<see cref="T:C5.Fun`2"/> with <code>R == bool</code>) defining the predicate</param>\r
-    /// <returns>the index, if found, a negative value else</returns>\r
-    public int FindLastIndex(Fun<T, bool> predicate)\r
-    {\r
-      int index = Count - 1;\r
-      foreach (T item in Backwards())\r
-      {\r
-        if (predicate(item))\r
-          return index;\r
-        index--;\r
-      }\r
-      return -1;\r
-    }\r
-\r
-  }\r
-\r
-\r
-  /// <summary>\r
-  /// Base class for collection classes of dynamic array type implementations.\r
-  /// </summary>\r
-  [Serializable]\r
-  public abstract class ArrayBase<T> : SequencedBase<T>\r
-  {\r
-    #region Fields\r
-    /// <summary>\r
-    /// The actual internal array container. Will be extended on demand.\r
-    /// </summary>\r
-    protected T[] array;\r
-\r
-    /// <summary>\r
-    /// The offset into the internal array container of the first item. The offset is 0 for a \r
-    /// base dynamic array and may be positive for an updatable view into a base dynamic array.\r
-    /// </summary>\r
-    protected int offset;\r
-    #endregion\r
-\r
-    #region Util\r
-    /// <summary>\r
-    /// Double the size of the internal array.\r
-    /// </summary>\r
-    protected virtual void expand()\r
-    {\r
-      expand(2 * array.Length, size);\r
-    }\r
-\r
-\r
-    /// <summary>\r
-    /// Expand the internal array container.\r
-    /// </summary>\r
-    /// <param name="newcapacity">The new size of the internal array - \r
-    /// will be rounded upwards to a power of 2.</param>\r
-    /// <param name="newsize">The (new) size of the (base) collection.</param>\r
-    protected virtual void expand(int newcapacity, int newsize)\r
-    {\r
-      Debug.Assert(newcapacity >= newsize);\r
-\r
-      int newlength = array.Length;\r
-\r
-      while (newlength < newcapacity) newlength *= 2;\r
-\r
-      T[] newarray = new T[newlength];\r
-\r
-      Array.Copy(array, newarray, newsize);\r
-      array = newarray;\r
-    }\r
-\r
-\r
-    /// <summary>\r
-    /// Insert an item at a specific index, moving items to the right\r
-    /// upwards and expanding the array if necessary.\r
-    /// </summary>\r
-    /// <param name="i">The index at which to insert.</param>\r
-    /// <param name="item">The item to insert.</param>\r
-    protected virtual void insert(int i, T item)\r
-    {\r
-      if (size == array.Length)\r
-        expand();\r
-\r
-      if (i < size)\r
-        Array.Copy(array, i, array, i + 1, size - i);\r
-\r
-      array[i] = item;\r
-      size++;\r
-    }\r
-\r
-    #endregion\r
-\r
-    #region Constructors\r
-\r
-    /// <summary>\r
-    /// Create an empty ArrayBase object.\r
-    /// </summary>\r
-    /// <param name="capacity">The initial capacity of the internal array container.\r
-    /// Will be rounded upwards to the nearest power of 2 greater than or equal to 8.</param>\r
-    /// <param name="itemequalityComparer">The item equalityComparer to use, primarily for item equality</param>\r
-    public ArrayBase(int capacity, SCG.IEqualityComparer<T> itemequalityComparer)\r
-      : base(itemequalityComparer)\r
-    {\r
-      int newlength = 8;\r
-      while (newlength < capacity) newlength *= 2;\r
-      array = new T[newlength];\r
-    }\r
-\r
-    #endregion\r
-\r
-    #region IIndexed members\r
-\r
-    /// <summary>\r
-    /// </summary>\r
-    /// <exception cref="ArgumentOutOfRangeException">If the arguments does not describe a \r
-    /// valid range in the indexed collection, cf. <see cref="M:C5.CollectionBase`1.checkRange(System.Int32,System.Int32)"/>.</exception>\r
-    /// <value>The directed collection of items in a specific index interval.</value>\r
-    /// <param name="start">The low index of the interval (inclusive).</param>\r
-    /// <param name="count">The size of the range.</param>\r
-    [Tested]\r
-    public virtual IDirectedCollectionValue<T> this[int start, int count]\r
-    {\r
-      [Tested]\r
-      get\r
-      {\r
-        checkRange(start, count);\r
-        return new Range(this, start, count, true);\r
-      }\r
-    }\r
-\r
-    #endregion\r
-\r
-    #region IEditableCollection members\r
-    /// <summary>\r
-    /// Remove all items and reset size of internal array container.\r
-    /// </summary>\r
-    [Tested]\r
-    public virtual void Clear()\r
-    {\r
-      updatecheck();\r
-      array = new T[8];\r
-      size = 0;\r
-    }\r
-\r
-\r
-    /// <summary>\r
-    /// Create an array containing (copies) of the items of this collection in enumeration order.\r
-    /// </summary>\r
-    /// <returns>The new array</returns>\r
-    [Tested]\r
-    public override T[] ToArray()\r
-    {\r
-      T[] res = new T[size];\r
-\r
-      Array.Copy(array, offset, res, 0, size);\r
-      return res;\r
-    }\r
-\r
-\r
-    /// <summary>\r
-    /// Perform an internal consistency (invariant) test on the array base.\r
-    /// </summary>\r
-    /// <returns>True if test succeeds.</returns>\r
-    [Tested]\r
-    public virtual bool Check()\r
-    {\r
-      bool retval = true;\r
-\r
-      if (size > array.Length)\r
-      {\r
-        Console.WriteLine("Bad size ({0}) > array.Length ({1})", size, array.Length);\r
-        return false;\r
-      }\r
-\r
-      for (int i = 0; i < size; i++)\r
-      {\r
-        if ((object)(array[i]) == null)\r
-        {\r
-          Console.WriteLine("Bad element: null at index {0}", i);\r
-          return false;\r
-        }\r
-      }\r
-\r
-      return retval;\r
-    }\r
-\r
-    #endregion\r
-\r
-    #region IDirectedCollection<T> Members\r
-\r
-    /// <summary>\r
-    /// Create a directed collection with the same contents as this one, but \r
-    /// opposite enumeration sequence.\r
-    /// </summary>\r
-    /// <returns>The mirrored collection.</returns>\r
-    [Tested]\r
-    public override IDirectedCollectionValue<T> Backwards() { return this[0, size].Backwards(); }\r
-\r
-    #endregion\r
-\r
-    /// <summary>\r
-    /// Choose some item of this collection. The result is the last item in the internal array,\r
-    /// making it efficient to remove.\r
-    /// </summary>\r
-    /// <exception cref="NoSuchItemException">if collection is empty.</exception>\r
-    /// <returns></returns>\r
-    public override T Choose() { if (size > 0) return array[size - 1]; throw new NoSuchItemException(); }\r
-\r
-    #region IEnumerable<T> Members\r
-    /// <summary>\r
-    /// Create an enumerator for this array based collection.\r
-    /// </summary>\r
-    /// <returns>The enumerator</returns>\r
-    [Tested]\r
-    public override SCG.IEnumerator<T> GetEnumerator()\r
-    {\r
-      int thestamp = stamp, theend = size + offset, thestart = offset;\r
-\r
-      for (int i = thestart; i < theend; i++)\r
-      {\r
-        modifycheck(thestamp);\r
-        yield return array[i];\r
-      }\r
-    }\r
-    #endregion\r
-\r
-    #region Range nested class\r
-    /// <summary>\r
-    /// A helper class for defining results of interval queries on array based collections.\r
-    /// </summary>\r
-    protected class Range : DirectedCollectionValueBase<T>, IDirectedCollectionValue<T>\r
-    {\r
-      int start, count, delta, stamp;\r
-\r
-      ArrayBase<T> thebase;\r
-\r
-\r
-      internal Range(ArrayBase<T> thebase, int start, int count, bool forwards)\r
-      {\r
-        this.thebase = thebase; stamp = thebase.stamp;\r
-        delta = forwards ? 1 : -1;\r
-        this.start = start + thebase.offset; this.count = count;\r
-      }\r
-\r
-      /// <summary>\r
-      /// \r
-      /// </summary>\r
-      /// <exception cref="CollectionModifiedException">if underlying collection has been modified.</exception>\r
-      /// <value>True if this collection is empty.</value>\r
-      public override bool IsEmpty { get { thebase.modifycheck(stamp); return count == 0; } }\r
-\r
-\r
-      /// <summary>\r
-      /// \r
-      /// </summary>\r
-      /// <exception cref="CollectionModifiedException">if underlying collection has been modified.</exception>\r
-      /// <value>The number of items in the range</value>\r
-      [Tested]\r
-      public override int Count { [Tested]get { thebase.modifycheck(stamp); return count; } }\r
-\r
-      /// <summary>\r
-      /// The value is symbolic indicating the type of asymptotic complexity\r
-      /// in terms of the size of this collection (worst-case or amortized as\r
-      /// relevant).\r
-      /// </summary>\r
-      /// <value>A characterization of the speed of the \r
-      /// <exception cref="CollectionModifiedException">if underlying collection has been modified.</exception>\r
-      /// <code>Count</code> property in this collection.</value>\r
-      public override Speed CountSpeed { get { thebase.modifycheck(stamp); return Speed.Constant; } }\r
-\r
-      /// <summary>\r
-      /// Choose some item of this collection. \r
-      /// </summary>\r
-      /// <exception cref="CollectionModifiedException">if underlying collection has been modified.</exception>\r
-      /// <exception cref="NoSuchItemException">if range is empty.</exception>\r
-      /// <returns></returns>\r
-      public override T Choose()\r
-      {\r
-        thebase.modifycheck(stamp);\r
-        if (count == 0)\r
-          throw new NoSuchItemException();\r
-        return thebase.array[start];\r
-      }\r
-\r
-\r
-      /// <summary>\r
-      /// Create an enumerator for this range of an array based collection.\r
-      /// </summary>\r
-      /// <exception cref="CollectionModifiedException">if underlying collection has been modified.</exception>\r
-      /// <returns>The enumerator</returns>\r
-      [Tested]\r
-      public override SCG.IEnumerator<T> GetEnumerator()\r
-      {\r
-        for (int i = 0; i < count; i++)\r
-        {\r
-          thebase.modifycheck(stamp);\r
-          yield return thebase.array[start + delta * i];\r
-        }\r
-      }\r
-\r
-\r
-      /// <summary>\r
-      /// Create a araay collection range with the same contents as this one, but \r
-      /// opposite enumeration sequence.\r
-      /// </summary>\r
-      /// <exception cref="CollectionModifiedException">if underlying collection has been modified.</exception>\r
-      /// <returns>The mirrored collection.</returns>\r
-      [Tested]\r
-      public override IDirectedCollectionValue<T> Backwards()\r
-      {\r
-        thebase.modifycheck(stamp);\r
-\r
-        Range res = (Range)MemberwiseClone();\r
-\r
-        res.delta = -delta;\r
-        res.start = start + (count - 1) * delta;\r
-        return res;\r
-      }\r
-\r
-\r
-      IDirectedEnumerable<T> C5.IDirectedEnumerable<T>.Backwards()\r
-      {\r
-        return Backwards();\r
-      }\r
-\r
-\r
-      /// <summary>\r
-      /// <code>Forwards</code> if same, else <code>Backwards</code>\r
-      /// </summary>\r
-      /// <exception cref="CollectionModifiedException">if underlying collection has been modified.</exception>\r
-      /// <value>The enumeration direction relative to the original collection.</value>\r
-      [Tested]\r
-      public override EnumerationDirection Direction\r
-      {\r
-        [Tested]\r
-        get\r
-        {\r
-          thebase.modifycheck(stamp);\r
-          return delta > 0 ? EnumerationDirection.Forwards : EnumerationDirection.Backwards;\r
-        }\r
-      }\r
-    }\r
-    #endregion\r
-  }\r
-}\r
+/*
+ Copyright (c) 2003-2006 Niels Kokholm and Peter Sestoft
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ SOFTWARE.
+*/
 
+#define IMPROVED_COLLECTION_HASHFUNCTION
+
+using System;
+using System.Diagnostics;
+using SCG = System.Collections.Generic;
+namespace C5
+{
+  /// <summary>
+  /// A base class for implementing an IEnumerable&lt;T&gt;
+  /// </summary>
+  [Serializable]
+  public abstract class EnumerableBase<T> : SCG.IEnumerable<T>
+  {
+    /// <summary>
+    /// Create an enumerator for this collection.
+    /// </summary>
+    /// <returns>The enumerator</returns>
+    public abstract SCG.IEnumerator<T> GetEnumerator();
+
+    /// <summary>
+    /// Count the number of items in an enumerable by enumeration
+    /// </summary>
+    /// <param name="items">The enumerable to count</param>
+    /// <returns>The size of the enumerable</returns>
+    [Tested]
+    protected static int countItems(SCG.IEnumerable<T> items)
+    {
+      ICollectionValue<T> jtems = items as ICollectionValue<T>;
+
+      if (jtems != null)
+        return jtems.Count;
+
+      int count = 0;
+
+      using (SCG.IEnumerator<T> e = items.GetEnumerator())
+        while (e.MoveNext()) count++;
+
+      return count;
+    }
+
+    #region IEnumerable Members
+
+    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
+    {
+      return GetEnumerator();
+    }
+
+    #endregion
+  }
+
+
+  /// <summary>
+  /// Base class for classes implementing ICollectionValue[T]
+  /// </summary>
+  [Serializable]
+  public abstract class CollectionValueBase<T> : EnumerableBase<T>, ICollectionValue<T>, IShowable
+  {
+    #region Event handling
+    EventBlock<T> eventBlock;
+    /// <summary>
+    /// 
+    /// </summary>
+    /// <value></value>
+    public virtual EventTypeEnum ListenableEvents { get { return 0; } }
+
+    /// <summary>
+    /// A flag bitmap of the events currently subscribed to by this collection.
+    /// </summary>
+    /// <value></value>
+    public virtual EventTypeEnum ActiveEvents { get { return eventBlock == null ? 0 : eventBlock.events; } }
+
+    private void checkWillListen(EventTypeEnum eventType)
+    {
+      if ((ListenableEvents & eventType) == 0)
+        throw new UnlistenableEventException();
+    }
+
+    /// <summary>
+    /// The change event. Will be raised for every change operation on the collection.
+    /// </summary>
+    public virtual event CollectionChangedHandler<T> CollectionChanged
+    {
+      add { checkWillListen(EventTypeEnum.Changed); (eventBlock ?? (eventBlock = new EventBlock<T>())).CollectionChanged += value; }
+      remove
+      {
+        checkWillListen(EventTypeEnum.Changed);
+        if (eventBlock != null)
+        {
+          eventBlock.CollectionChanged -= value;
+          if (eventBlock.events == 0) eventBlock = null;
+        }
+      }
+    }
+    /// <summary>
+    /// Fire the CollectionChanged event
+    /// </summary>
+    protected virtual void raiseCollectionChanged()
+    { if (eventBlock != null) eventBlock.raiseCollectionChanged(this); }
+
+    /// <summary>
+    /// The clear event. Will be raised for every Clear operation on the collection.
+    /// </summary>
+    public virtual event CollectionClearedHandler<T> CollectionCleared
+    {
+      add { checkWillListen(EventTypeEnum.Cleared); (eventBlock ?? (eventBlock = new EventBlock<T>())).CollectionCleared += value; }
+      remove
+      {
+        checkWillListen(EventTypeEnum.Cleared);
+        if (eventBlock != null)
+        {
+          eventBlock.CollectionCleared -= value;
+          if (eventBlock.events == 0) eventBlock = null;
+        }
+      }
+    }
+    /// <summary>
+    /// Fire the CollectionCleared event
+    /// </summary>
+    protected virtual void raiseCollectionCleared(bool full, int count)
+    { if (eventBlock != null) eventBlock.raiseCollectionCleared(this, full, count); }
+
+    /// <summary>
+    /// Fire the CollectionCleared event
+    /// </summary>
+    protected virtual void raiseCollectionCleared(bool full, int count, int? offset)
+    { if (eventBlock != null) eventBlock.raiseCollectionCleared(this, full, count, offset); }
+
+    /// <summary>
+    /// The item added  event. Will be raised for every individual addition to the collection.
+    /// </summary>
+    public virtual event ItemsAddedHandler<T> ItemsAdded
+    {
+      add { checkWillListen(EventTypeEnum.Added); (eventBlock ?? (eventBlock = new EventBlock<T>())).ItemsAdded += value; }
+      remove
+      {
+        checkWillListen(EventTypeEnum.Added);
+        if (eventBlock != null)
+        {
+          eventBlock.ItemsAdded -= value;
+          if (eventBlock.events == 0) eventBlock = null;
+        }
+      }
+    }
+    /// <summary>
+    /// Fire the ItemsAdded event
+    /// </summary>
+    /// <param name="item">The item that was added</param>
+    /// <param name="count"></param>
+    protected virtual void raiseItemsAdded(T item, int count)
+    { if (eventBlock != null) eventBlock.raiseItemsAdded(this, item, count); }
+
+    /// <summary>
+    /// The item removed event. Will be raised for every individual removal from the collection.
+    /// </summary>
+    public virtual event ItemsRemovedHandler<T> ItemsRemoved
+    {
+      add { checkWillListen(EventTypeEnum.Removed); (eventBlock ?? (eventBlock = new EventBlock<T>())).ItemsRemoved += value; }
+      remove
+      {
+        checkWillListen(EventTypeEnum.Removed);
+        if (eventBlock != null)
+        {
+          eventBlock.ItemsRemoved -= value;
+          if (eventBlock.events == 0) eventBlock = null;
+        }
+      }
+    }
+    /// <summary>
+    /// Fire the ItemsRemoved event
+    /// </summary>
+    /// <param name="item">The item that was removed</param>
+    /// <param name="count"></param>
+    protected virtual void raiseItemsRemoved(T item, int count)
+    { if (eventBlock != null) eventBlock.raiseItemsRemoved(this, item, count); }
+
+    /// <summary>
+    /// The item added  event. Will be raised for every individual addition to the collection.
+    /// </summary>
+    public virtual event ItemInsertedHandler<T> ItemInserted
+    {
+      add { checkWillListen(EventTypeEnum.Inserted); (eventBlock ?? (eventBlock = new EventBlock<T>())).ItemInserted += value; }
+      remove
+      {
+        checkWillListen(EventTypeEnum.Inserted);
+        if (eventBlock != null)
+        {
+          eventBlock.ItemInserted -= value;
+          if (eventBlock.events == 0) eventBlock = null;
+        }
+      }
+    }
+    /// <summary>
+    /// Fire the ItemInserted event
+    /// </summary>
+    /// <param name="item">The item that was added</param>
+    /// <param name="index"></param>
+    protected virtual void raiseItemInserted(T item, int index)
+    { if (eventBlock != null) eventBlock.raiseItemInserted(this, item, index); }
+
+    /// <summary>
+    /// The item removed event. Will be raised for every individual removal from the collection.
+    /// </summary>
+    public virtual event ItemRemovedAtHandler<T> ItemRemovedAt
+    {
+      add { checkWillListen(EventTypeEnum.RemovedAt); (eventBlock ?? (eventBlock = new EventBlock<T>())).ItemRemovedAt += value; }
+      remove
+      {
+        checkWillListen(EventTypeEnum.RemovedAt);
+        if (eventBlock != null)
+        {
+          eventBlock.ItemRemovedAt -= value;
+          if (eventBlock.events == 0) eventBlock = null;
+        }
+      }
+    }
+    /// <summary> 
+    /// Fire the ItemRemovedAt event
+    /// </summary>
+    /// <param name="item">The item that was removed</param>
+    /// <param name="index"></param>
+    protected virtual void raiseItemRemovedAt(T item, int index)
+    { if (eventBlock != null) eventBlock.raiseItemRemovedAt(this, item, index); }
+
+    #region Event support for IList
+    /// <summary>
+    /// 
+    /// </summary>
+    /// <param name="index"></param>
+    /// <param name="value"></param>
+    /// <param name="item"></param>
+    protected virtual void raiseForSetThis(int index, T value, T item)
+    {
+      if (ActiveEvents != 0)
+      {
+        raiseItemsRemoved(item, 1);
+        raiseItemRemovedAt(item, index);
+        raiseItemsAdded(value, 1);
+        raiseItemInserted(value, index);
+        raiseCollectionChanged();
+      }
+    }
+    /// <summary>
+    /// 
+    /// </summary>
+    /// <param name="i"></param>
+    /// <param name="item"></param>
+    protected virtual void raiseForInsert(int i, T item)
+    {
+      if (ActiveEvents != 0)
+      {
+        raiseItemInserted(item, i);
+        raiseItemsAdded(item, 1);
+        raiseCollectionChanged();
+      }
+    }
+
+    /// <summary>
+    /// 
+    /// </summary>
+    /// <param name="item"></param>
+    protected void raiseForRemove(T item)
+    {
+      if (ActiveEvents != 0)
+      {
+        raiseItemsRemoved(item, 1);
+        raiseCollectionChanged();
+      }
+    }
+
+    /// <summary>
+    /// 
+    /// </summary>
+    /// <param name="item"></param>
+    /// <param name="count"></param>
+    protected void raiseForRemove(T item, int count)
+    {
+      if (ActiveEvents != 0)
+      {
+        raiseItemsRemoved(item, count);
+        raiseCollectionChanged();
+      }
+    }
+
+    /// <summary>
+    /// 
+    /// </summary>
+    /// <param name="index"></param>
+    /// <param name="item"></param>
+    protected void raiseForRemoveAt(int index, T item)
+    {
+      if (ActiveEvents != 0)
+      {
+        raiseItemRemovedAt(item, index);
+        raiseItemsRemoved(item, 1);
+        raiseCollectionChanged();
+      }
+    }
+
+    #endregion
+
+    #region Event  Support for ICollection
+    /// <summary>
+    /// 
+    /// </summary>
+    /// <param name="newitem"></param>
+    /// <param name="olditem"></param>
+    protected virtual void raiseForUpdate(T newitem, T olditem)
+    {
+      if (ActiveEvents != 0)
+      {
+        raiseItemsRemoved(olditem, 1);
+        raiseItemsAdded(newitem, 1);
+        raiseCollectionChanged();
+      }
+    }
+    /// <summary>
+    /// 
+    /// </summary>
+    /// <param name="newitem"></param>
+    /// <param name="olditem"></param>
+    /// <param name="count"></param>
+    protected virtual void raiseForUpdate(T newitem, T olditem, int count)
+    {
+      if (ActiveEvents != 0)
+      {
+        raiseItemsRemoved(olditem, count);
+        raiseItemsAdded(newitem, count);
+        raiseCollectionChanged();
+      }
+    }
+    /// <summary>
+    /// 
+    /// </summary>
+    /// <param name="item"></param>
+    protected virtual void raiseForAdd(T item)
+    {
+      if (ActiveEvents != 0)
+      {
+        raiseItemsAdded(item, 1);
+        raiseCollectionChanged();
+      }
+    }
+    /// <summary>
+    /// 
+    /// </summary>
+    /// <param name="wasRemoved"></param>
+    protected virtual void raiseForRemoveAll(ICollectionValue<T> wasRemoved)
+    {
+      if ((ActiveEvents & EventTypeEnum.Removed) != 0)
+        foreach (T item in wasRemoved)
+          raiseItemsRemoved(item, 1);
+      if (wasRemoved != null && wasRemoved.Count > 0)
+        raiseCollectionChanged();
+    }
+
+    /// <summary>
+    /// 
+    /// </summary>
+    protected class RaiseForRemoveAllHandler
+    {
+      CollectionValueBase<T> collection;
+      CircularQueue<T> wasRemoved;
+      bool wasChanged = false;
+
+      /// <summary>
+      /// 
+      /// </summary>
+      /// <param name="collection"></param>
+      public RaiseForRemoveAllHandler(CollectionValueBase<T> collection)
+      {
+        this.collection = collection;
+        mustFireRemoved = (collection.ActiveEvents & EventTypeEnum.Removed) != 0;
+        MustFire = (collection.ActiveEvents & (EventTypeEnum.Removed | EventTypeEnum.Changed)) != 0;
+      }
+
+      bool mustFireRemoved;
+      /// <summary>
+      /// 
+      /// </summary>
+      public readonly bool MustFire;
+
+      /// <summary>
+      /// 
+      /// </summary>
+      /// <param name="item"></param>
+      public void Remove(T item)
+      {
+        if (mustFireRemoved)
+        {
+          if (wasRemoved == null)
+            wasRemoved = new CircularQueue<T>();
+          wasRemoved.Enqueue(item);
+        }
+        if (!wasChanged)
+          wasChanged = true;
+      }
+
+      /// <summary>
+      /// 
+      /// </summary>
+      public void Raise()
+      {
+        if (wasRemoved != null)
+          foreach (T item in wasRemoved)
+            collection.raiseItemsRemoved(item, 1);
+        if (wasChanged)
+          collection.raiseCollectionChanged();
+      }
+    }
+    #endregion
+
+    #endregion
+
+    /// <summary>
+    /// Check if collection is empty.
+    /// </summary>
+    /// <value>True if empty</value>
+    public abstract bool IsEmpty { get;}
+
+    /// <summary>
+    /// The number of items in this collection.
+    /// </summary>
+    /// <value></value>
+    public abstract int Count { get;}
+
+    /// <summary>
+    /// The value is symbolic indicating the type of asymptotic complexity
+    /// in terms of the size of this collection (worst-case or amortized as
+    /// relevant).
+    /// </summary>
+    /// <value>A characterization of the speed of the 
+    /// <code>Count</code> property in this collection.</value>
+    public abstract Speed CountSpeed { get; }
+
+    /// <summary>
+    /// Copy the items of this collection to part of an array.
+    /// </summary>
+    /// <exception cref="ArgumentOutOfRangeException"> if <code>index</code> 
+    /// is not a valid index
+    /// into the array (i.e. negative or greater than the size of the array)
+    /// or the array does not have room for the items.</exception>
+    /// <param name="array">The array to copy to.</param>
+    /// <param name="index">The starting index.</param>
+    [Tested]
+    public virtual void CopyTo(T[] array, int index)
+    {
+      if (index < 0 || index + Count > array.Length)
+        throw new ArgumentOutOfRangeException();
+
+      foreach (T item in this) array[index++] = item;
+    }
+
+    /// <summary>
+    /// Create an array with the items of this collection (in the same order as an
+    /// enumerator would output them).
+    /// </summary>
+    /// <returns>The array</returns>
+    //[Tested]
+    public virtual T[] ToArray()
+    {
+      T[] res = new T[Count];
+      int i = 0;
+
+      foreach (T item in this) res[i++] = item;
+
+      return res;
+    }
+
+    /// <summary>
+    /// Apply an single argument action, <see cref="T:C5.Act`1"/> to this enumerable
+    /// </summary>
+    /// <param name="action">The action delegate</param>
+    [Tested]
+    public virtual void Apply(Act<T> action)
+    {
+      foreach (T item in this)
+        action(item);
+    }
+
+
+    /// <summary>
+    /// Check if there exists an item  that satisfies a
+    /// specific predicate in this collection.
+    /// </summary>
+    /// <param name="predicate">A delegate 
+    /// (<see cref="T:C5.Fun`2"/> with <code>R = bool</code>) 
+    /// defining the predicate</param>
+    /// <returns>True if such an item exists</returns>
+    [Tested]
+    public virtual bool Exists(Fun<T, bool> predicate)
+    {
+      foreach (T item in this)
+        if (predicate(item))
+          return true;
+
+      return false;
+    }
+
+    /// <summary>
+    /// Check if there exists an item  that satisfies a
+    /// specific predicate in this collection and return the first one in enumeration order.
+    /// </summary>
+    /// <param name="predicate">A delegate 
+    /// (<see cref="T:C5.Fun`2"/> with <code>R == bool</code>) defining the predicate</param>
+    /// <param name="item"></param>
+    /// <returns>True is such an item exists</returns>
+    public virtual bool Find(Fun<T, bool> predicate, out T item)
+    {
+      foreach (T jtem in this)
+        if (predicate(jtem))
+        {
+          item = jtem;
+          return true;
+        }
+      item = default(T);
+      return false;
+    }
+
+    /// <summary>
+    /// Check if all items in this collection satisfies a specific predicate.
+    /// </summary>
+    /// <param name="predicate">A delegate 
+    /// (<see cref="T:C5.Fun`2"/> with <code>R = bool</code>) 
+    /// defining the predicate</param>
+    /// <returns>True if all items satisfies the predicate</returns>
+    [Tested]
+    public virtual bool All(Fun<T, bool> predicate)
+    {
+      foreach (T item in this)
+        if (!predicate(item))
+          return false;
+
+      return true;
+    }
+
+    /// <summary>
+    /// Create an enumerable, enumerating the items of this collection that satisfies 
+    /// a certain condition.
+    /// </summary>
+    /// <param name="predicate">A delegate 
+    /// (<see cref="T:C5.Fun`2"/> with <code>R = bool</code>) 
+    /// defining the predicate</param>
+    /// <returns>The filtered enumerable</returns>
+    public virtual SCG.IEnumerable<T> Filter(Fun<T, bool> predicate)
+    {
+      foreach (T item in this)
+        if (predicate(item))
+          yield return item;
+    }
+
+    /// <summary>
+    /// Choose some item of this collection. 
+    /// </summary>
+    /// <exception cref="NoSuchItemException">if collection is empty.</exception>
+    /// <returns></returns>
+    public abstract T Choose();
+
+
+    /// <summary>
+    /// Create an enumerator for this collection.
+    /// </summary>
+    /// <returns>The enumerator</returns>
+    public override abstract SCG.IEnumerator<T> GetEnumerator();
+
+    #region IShowable Members
+
+    /// <summary>
+    /// 
+    /// </summary>
+    /// <param name="stringbuilder"></param>
+    /// <param name="rest"></param>
+    /// <param name="formatProvider"></param>
+    /// <returns></returns>
+    public virtual bool Show(System.Text.StringBuilder stringbuilder, ref int rest, IFormatProvider formatProvider)
+    {
+      return Showing.ShowCollectionValue<T>(this, stringbuilder, ref rest, formatProvider);
+    }
+    #endregion
+
+    #region IFormattable Members
+
+    /// <summary>
+    /// 
+    /// </summary>
+    /// <param name="format"></param>
+    /// <param name="formatProvider"></param>
+    /// <returns></returns>
+    public virtual string ToString(string format, IFormatProvider formatProvider)
+    {
+      return Showing.ShowString(this, format, formatProvider);
+    }
+
+    #endregion
+
+    /// <summary>
+    /// 
+    /// </summary>
+    /// <returns></returns>
+    public override string ToString()
+    {
+      return ToString(null, null);
+    }
+
+  }
+
+  /// <summary>
+  /// 
+  /// </summary>
+  /// <typeparam name="T"></typeparam>
+  public abstract class DirectedCollectionValueBase<T> : CollectionValueBase<T>, IDirectedCollectionValue<T>
+  {
+    /// <summary>
+    /// <code>Forwards</code> if same, else <code>Backwards</code>
+    /// </summary>
+    /// <value>The enumeration direction relative to the original collection.</value>
+    public virtual EnumerationDirection Direction { [Tested]get { return EnumerationDirection.Forwards; } }
+
+    /// <summary>
+    /// 
+    /// </summary>
+    /// <returns></returns>
+    public abstract IDirectedCollectionValue<T> Backwards();
+
+    IDirectedEnumerable<T> IDirectedEnumerable<T>.Backwards() { return this.Backwards(); }
+
+    /// <summary>
+    /// Check if there exists an item  that satisfies a
+    /// specific predicate in this collection and return the first one in enumeration order.
+    /// </summary>
+    /// <param name="predicate">A delegate 
+    /// (<see cref="T:C5.Fun`2"/> with <code>R == bool</code>) defining the predicate</param>
+    /// <param name="item"></param>
+    /// <returns>True is such an item exists</returns>
+    public virtual bool FindLast(Fun<T, bool> predicate, out T item)
+    {
+      foreach (T jtem in Backwards())
+        if (predicate(jtem))
+        {
+          item = jtem;
+          return true;
+        }
+      item = default(T);
+      return false;
+    }
+  }
+
+  /// <summary>
+  /// Base class (abstract) for ICollection implementations.
+  /// </summary>
+  [Serializable]
+  public abstract class CollectionBase<T> : CollectionValueBase<T>
+  {
+    #region Fields
+
+    /// <summary>
+    /// The underlying field of the ReadOnly property
+    /// </summary>
+    protected bool isReadOnlyBase = false;
+
+    /// <summary>
+    /// The current stamp value
+    /// </summary>
+    protected int stamp;
+
+    /// <summary>
+    /// The number of items in the collection
+    /// </summary>
+    protected int size;
+
+    /// <summary>
+    /// The item equalityComparer of the collection
+    /// </summary>
+    protected readonly SCG.IEqualityComparer<T> itemequalityComparer;
+
+    int iUnSequencedHashCode, iUnSequencedHashCodeStamp = -1;
+
+    #endregion
+
+    /// <summary>
+    /// 
+    /// </summary>
+    /// <param name="itemequalityComparer"></param>
+    protected CollectionBase(SCG.IEqualityComparer<T> itemequalityComparer)
+    {
+      if (itemequalityComparer == null)
+        throw new NullReferenceException("Item EqualityComparer cannot be null.");
+      this.itemequalityComparer = itemequalityComparer;
+    }
+
+    #region Util
+
+    /// <summary>
+    /// Utility method for range checking.
+    /// </summary>
+    /// <exception cref="ArgumentOutOfRangeException"> if the start or count is negative or
+    ///  if the range does not fit within collection size.</exception>
+    /// <param name="start">start of range</param>
+    /// <param name="count">size of range</param>
+    [Tested]
+    protected void checkRange(int start, int count)
+    {
+      if (start < 0 || count < 0 || start + count > size)
+        throw new ArgumentOutOfRangeException();
+    }
+
+
+    /// <summary>
+    /// Compute the unsequenced hash code of a collection
+    /// </summary>
+    /// <param name="items">The collection to compute hash code for</param>
+    /// <param name="itemequalityComparer">The item equalityComparer</param>
+    /// <returns>The hash code</returns>
+    [Tested]
+    public static int ComputeHashCode(ICollectionValue<T> items, SCG.IEqualityComparer<T> itemequalityComparer)
+    {
+      int h = 0;
+
+#if IMPROVED_COLLECTION_HASHFUNCTION
+      //But still heuristic: 
+      //Note: the three odd factors should really be random, 
+      //but there will be a problem with serialization/deserialization!
+      //Two products is too few
+      foreach (T item in items)
+      {
+        uint h1 = (uint)itemequalityComparer.GetHashCode(item);
+
+        h += (int)((h1 * 1529784657 + 1) ^ (h1 * 2912831877) ^ (h1 * 1118771817 + 2));
+      }
+
+      return h;
+      /*
+            The pairs (-1657792980, -1570288808) and (1862883298, -272461342) gives the same
+            unsequenced hashcode with this hashfunction. The pair was found with code like
+
+            HashDictionary<int, int[]> set = new HashDictionary<int, int[]>();
+            Random rnd = new C5Random(12345);
+            while (true)
+            {
+                int[] a = new int[2];
+                a[0] = rnd.Next(); a[1] = rnd.Next();
+                int h = unsequencedhashcode(a);
+                int[] b = a;
+                if (set.FindOrAdd(h, ref b))
+                {
+                    Console.WriteLine("Code {5}, Pair ({1},{2}) number {0} matched other pair ({3},{4})", set.Count, a[0], a[1], b[0], b[1], h);
+                }
+            }
+            */
+#else
+            foreach (T item in items)
+                               h ^= itemequalityComparer.GetHashCode(item);
+
+                       return (items.Count << 16) + h;
 #endif
+    }
+
+    static Type isortedtype = typeof(ISorted<T>);
+
+    /// <summary>
+    /// Examine if collection1 and collection2 are equal as unsequenced collections
+    /// using the specified item equalityComparer (assumed compatible with the two collections).
+    /// </summary>
+    /// <param name="collection1">The first collection</param>
+    /// <param name="collection2">The second collection</param>
+    /// <param name="itemequalityComparer">The item equalityComparer to use for comparison</param>
+    /// <returns>True if equal</returns>
+    [Tested]
+    public static bool StaticEquals(ICollection<T> collection1, ICollection<T> collection2, SCG.IEqualityComparer<T> itemequalityComparer)
+    {
+      if (object.ReferenceEquals(collection1, collection2))
+        return true;
+
+      // bug20070227:
+      if (collection1 == null || collection2 == null)
+        return false;
+
+      if (collection1.Count != collection2.Count)
+        return false;
+
+      //This way we might run through both enumerations twice, but
+      //probably not (if the hash codes are good)
+      //TODO: check equal equalityComparers, at least here!
+      if (collection1.GetUnsequencedHashCode() != collection2.GetUnsequencedHashCode())
+        return false;
+
+      //TODO: move this to the sorted implementation classes? 
+      //Really depends on speed of InstanceOfType: we could save a cast
+      {
+        ISorted<T> stit, stat;
+        if ((stit = collection1 as ISorted<T>) != null && (stat = collection2 as ISorted<T>) != null && stit.Comparer == stat.Comparer)
+        {
+          using (SCG.IEnumerator<T> dat = collection2.GetEnumerator(), dit = collection1.GetEnumerator())
+          {
+            while (dit.MoveNext())
+            {
+              dat.MoveNext();
+              if (!itemequalityComparer.Equals(dit.Current, dat.Current))
+                return false;
+            }
+            return true;
+          }
+        }
+      }
+
+      if (!collection1.AllowsDuplicates && (collection2.AllowsDuplicates || collection2.ContainsSpeed >= collection1.ContainsSpeed))
+      {
+        foreach (T x in collection1) if (!collection2.Contains(x)) return false;
+      }
+      else if (!collection2.AllowsDuplicates)
+      {
+        foreach (T x in collection2) if (!collection1.Contains(x)) return false;
+      }
+      // Now tit.AllowsDuplicates && tat.AllowsDuplicates
+      else if (collection1.DuplicatesByCounting && collection2.DuplicatesByCounting)
+      {
+        foreach (T item in collection2) if (collection1.ContainsCount(item) != collection2.ContainsCount(item)) return false;
+      }
+      else
+      {
+        // To avoid an O(n^2) algorithm, we make an aux hashtable to hold the count of items
+        // bug20101103: HashDictionary<T, int> dict = new HashDictionary<T, int>();
+        HashDictionary<T, int> dict = new HashDictionary<T, int>(itemequalityComparer);
+        foreach (T item in collection2)
+        {
+          int count = 1;
+          if (dict.FindOrAdd(item, ref count))
+            dict[item] = count + 1;
+        }
+        foreach (T item in collection1)
+        {
+          int count;
+          if (dict.Find(item, out count) && count > 0)
+            dict[item] = count - 1;
+          else
+            return false;
+        }
+        return true;
+      }
+
+      return true;
+    }
+
+
+    /// <summary>
+    /// Get the unsequenced collection hash code of this collection: from the cached 
+    /// value if present and up to date, else (re)compute.
+    /// </summary>
+    /// <returns>The hash code</returns>
+    public virtual int GetUnsequencedHashCode()
+    {
+      if (iUnSequencedHashCodeStamp == stamp)
+        return iUnSequencedHashCode;
+
+      iUnSequencedHashCode = ComputeHashCode(this, itemequalityComparer);
+      iUnSequencedHashCodeStamp = stamp;
+      return iUnSequencedHashCode;
+    }
+
+
+    /// <summary>
+    /// Check if the contents of otherCollection is equal to the contents of this
+    /// in the unsequenced sense.  Uses the item equality comparer of this collection
+    /// </summary>
+    /// <param name="otherCollection">The collection to compare to.</param>
+    /// <returns>True if  equal</returns>
+    public virtual bool UnsequencedEquals(ICollection<T> otherCollection)
+    {
+      return otherCollection != null && StaticEquals((ICollection<T>)this, otherCollection, itemequalityComparer);
+    }
+
+
+    /// <summary>
+    /// Check if the collection has been modified since a specified time, expressed as a stamp value.
+    /// </summary>
+    /// <exception cref="CollectionModifiedException"> if this collection has been updated 
+    /// since a target time</exception>
+    /// <param name="thestamp">The stamp identifying the target time</param>
+    protected virtual void modifycheck(int thestamp)
+    {
+      if (this.stamp != thestamp)
+        throw new CollectionModifiedException();
+    }
+
+
+    /// <summary>
+    /// Check if it is valid to perform update operations, and if so increment stamp.
+    /// </summary>
+    /// <exception cref="ReadOnlyCollectionException">If colection is read-only</exception>
+    protected virtual void updatecheck()
+    {
+      if (isReadOnlyBase)
+        throw new ReadOnlyCollectionException();
+
+      stamp++;
+    }
+
+    #endregion
+
+    #region ICollection<T> members
+
+    /// <summary>
+    /// 
+    /// </summary>
+    /// <value>True if this collection is read only</value>
+    [Tested]
+    public virtual bool IsReadOnly { [Tested]get { return isReadOnlyBase; } }
+
+    #endregion
+
+    #region ICollectionValue<T> members
+    /// <summary>
+    /// 
+    /// </summary>
+    /// <value>The size of this collection</value>
+    [Tested]
+    public override int Count { [Tested]get { return size; } }
+
+    /// <summary>
+    /// The value is symbolic indicating the type of asymptotic complexity
+    /// in terms of the size of this collection (worst-case or amortized as
+    /// relevant).
+    /// </summary>
+    /// <value>A characterization of the speed of the 
+    /// <code>Count</code> property in this collection.</value>
+    public override Speed CountSpeed { get { return Speed.Constant; } }
+
+
+    #endregion
+
+    #region IExtensible<T> members
+
+    /// <summary>
+    /// 
+    /// </summary>
+    /// <value></value>
+    public virtual SCG.IEqualityComparer<T> EqualityComparer { get { return itemequalityComparer; } }
+
+    /// <summary>
+    /// 
+    /// </summary>
+    /// <value>True if this collection is empty</value>
+    [Tested]
+    public override bool IsEmpty { [Tested]get { return size == 0; } }
+
+    #endregion
+
+    #region IEnumerable<T> Members
+    /// <summary>
+    /// Create an enumerator for this collection.
+    /// </summary>
+    /// <returns>The enumerator</returns>
+    public override abstract SCG.IEnumerator<T> GetEnumerator();
+    #endregion
+  }
+
+  /// <summary>
+  /// 
+  /// </summary>
+  /// <typeparam name="T"></typeparam>
+  [Serializable]
+  public abstract class DirectedCollectionBase<T> : CollectionBase<T>, IDirectedCollectionValue<T>
+  {
+    /// <summary>
+    /// 
+    /// </summary>
+    /// <param name="itemequalityComparer"></param>
+    protected DirectedCollectionBase(SCG.IEqualityComparer<T> itemequalityComparer) : base(itemequalityComparer) { }
+    /// <summary>
+    /// <code>Forwards</code> if same, else <code>Backwards</code>
+    /// </summary>
+    /// <value>The enumeration direction relative to the original collection.</value>
+    public virtual EnumerationDirection Direction { [Tested]get { return EnumerationDirection.Forwards; } }
+
+    /// <summary>
+    /// 
+    /// </summary>
+    /// <returns></returns>
+    public abstract IDirectedCollectionValue<T> Backwards();
+
+    IDirectedEnumerable<T> IDirectedEnumerable<T>.Backwards() { return this.Backwards(); }
+
+    /// <summary>
+    /// Check if there exists an item  that satisfies a
+    /// specific predicate in this collection and return the first one in enumeration order.
+    /// </summary>
+    /// <param name="predicate">A delegate 
+    /// (<see cref="T:C5.Fun`2"/> with <code>R == bool</code>) defining the predicate</param>
+    /// <param name="item"></param>
+    /// <returns>True is such an item exists</returns>
+    public virtual bool FindLast(Fun<T, bool> predicate, out T item)
+    {
+      foreach (T jtem in Backwards())
+        if (predicate(jtem))
+        {
+          item = jtem;
+          return true;
+        }
+      item = default(T);
+      return false;
+    }
+  }
+
+  /// <summary>
+  /// Base class (abstract) for sequenced collection implementations.
+  /// </summary>
+  [Serializable]
+  public abstract class SequencedBase<T> : DirectedCollectionBase<T>, IDirectedCollectionValue<T>
+  {
+    #region Fields
+
+    int iSequencedHashCode, iSequencedHashCodeStamp = -1;
+
+    #endregion
+
+    /// <summary>
+    /// 
+    /// </summary>
+    /// <param name="itemequalityComparer"></param>
+    protected SequencedBase(SCG.IEqualityComparer<T> itemequalityComparer) : base(itemequalityComparer) { }
+
+    #region Util
+
+    //TODO: make random for release
+    const int HASHFACTOR = 31;
+
+    /// <summary>
+    /// Compute the unsequenced hash code of a collection
+    /// </summary>
+    /// <param name="items">The collection to compute hash code for</param>
+    /// <param name="itemequalityComparer">The item equalityComparer</param>
+    /// <returns>The hash code</returns>
+    [Tested]
+    public static int ComputeHashCode(ISequenced<T> items, SCG.IEqualityComparer<T> itemequalityComparer)
+    {
+      //NOTE: It must be possible to devise a much stronger combined hashcode, 
+      //but unfortunately, it has to be universal. OR we could use a (strong)
+      //family and initialise its parameter randomly at load time of this class!
+      //(We would not want to have yet a flag to check for invalidation?!)
+      //NBNBNB: the current hashcode has the very bad property that items with hashcode 0
+      // is ignored.
+      int iIndexedHashCode = 0;
+
+      foreach (T item in items)
+        iIndexedHashCode = iIndexedHashCode * HASHFACTOR + itemequalityComparer.GetHashCode(item);
+
+      return iIndexedHashCode;
+    }
+
+
+    /// <summary>
+    /// Examine if tit and tat are equal as sequenced collections
+    /// using the specified item equalityComparer (assumed compatible with the two collections).
+    /// </summary>
+    /// <param name="collection1">The first collection</param>
+    /// <param name="collection2">The second collection</param>
+    /// <param name="itemequalityComparer">The item equalityComparer to use for comparison</param>
+    /// <returns>True if equal</returns>
+    [Tested]
+    public static bool StaticEquals(ISequenced<T> collection1, ISequenced<T> collection2, SCG.IEqualityComparer<T> itemequalityComparer)
+    {
+      if (object.ReferenceEquals(collection1, collection2))
+        return true;
+
+      if (collection1.Count != collection2.Count)
+        return false;
+
+      //This way we might run through both enumerations twice, but
+      //probably not (if the hash codes are good)
+      if (collection1.GetSequencedHashCode() != collection2.GetSequencedHashCode())
+        return false;
+
+      using (SCG.IEnumerator<T> dat = collection2.GetEnumerator(), dit = collection1.GetEnumerator())
+      {
+        while (dit.MoveNext())
+        {
+          dat.MoveNext();
+          if (!itemequalityComparer.Equals(dit.Current, dat.Current))
+            return false;
+        }
+      }
+
+      return true;
+    }
+
+
+    /// <summary>
+    /// Get the sequenced collection hash code of this collection: from the cached 
+    /// value if present and up to date, else (re)compute.
+    /// </summary>
+    /// <returns>The hash code</returns>
+    public virtual int GetSequencedHashCode()
+    {
+      if (iSequencedHashCodeStamp == stamp)
+        return iSequencedHashCode;
+
+      iSequencedHashCode = ComputeHashCode((ISequenced<T>)this, itemequalityComparer);
+      iSequencedHashCodeStamp = stamp;
+      return iSequencedHashCode;
+    }
+
+
+    /// <summary>
+    /// Check if the contents of that is equal to the contents of this
+    /// in the sequenced sense. Using the item equalityComparer of this collection.
+    /// </summary>
+    /// <param name="otherCollection">The collection to compare to.</param>
+    /// <returns>True if  equal</returns>
+    public virtual bool SequencedEquals(ISequenced<T> otherCollection)
+    {
+      return StaticEquals((ISequenced<T>)this, otherCollection, itemequalityComparer);
+    }
+
+
+    #endregion
+
+    /// <summary>
+    /// Create an enumerator for this collection.
+    /// </summary>
+    /// <returns>The enumerator</returns>
+    public override abstract SCG.IEnumerator<T> GetEnumerator();
+
+    /// <summary>
+    /// <code>Forwards</code> if same, else <code>Backwards</code>
+    /// </summary>
+    /// <value>The enumeration direction relative to the original collection.</value>
+    [Tested]
+    public override EnumerationDirection Direction { [Tested]get { return EnumerationDirection.Forwards; } }
+
+    /// <summary>
+    /// Check if there exists an item  that satisfies a
+    /// specific predicate in this collection and return the index of the first one.
+    /// </summary>
+    /// <param name="predicate">A delegate 
+    /// (<see cref="T:C5.Fun`2"/> with <code>R == bool</code>) defining the predicate</param>
+    /// <returns>the index, if found, a negative value else</returns>
+    public int FindIndex(Fun<T, bool> predicate)
+    {
+      int index = 0;
+      foreach (T item in this)
+      {
+        if (predicate(item))
+          return index;
+        index++;
+      }
+      return -1;
+    }
+
+    /// <summary>
+    /// Check if there exists an item  that satisfies a
+    /// specific predicate in this collection and return the index of the last one.
+    /// </summary>
+    /// <param name="predicate">A delegate 
+    /// (<see cref="T:C5.Fun`2"/> with <code>R == bool</code>) defining the predicate</param>
+    /// <returns>the index, if found, a negative value else</returns>
+    public int FindLastIndex(Fun<T, bool> predicate)
+    {
+      int index = Count - 1;
+      foreach (T item in Backwards())
+      {
+        if (predicate(item))
+          return index;
+        index--;
+      }
+      return -1;
+    }
+
+  }
+
+
+  /// <summary>
+  /// Base class for collection classes of dynamic array type implementations.
+  /// </summary>
+  [Serializable]
+  public abstract class ArrayBase<T> : SequencedBase<T>
+  {
+    #region Fields
+    /// <summary>
+    /// The actual internal array container. Will be extended on demand.
+    /// </summary>
+    protected T[] array;
+
+    /// <summary>
+    /// The offset into the internal array container of the first item. The offset is 0 for a 
+    /// base dynamic array and may be positive for an updatable view into a base dynamic array.
+    /// </summary>
+    protected int offset;
+    #endregion
+
+    #region Util
+    /// <summary>
+    /// Double the size of the internal array.
+    /// </summary>
+    protected virtual void expand()
+    {
+      expand(2 * array.Length, size);
+    }
+
+
+    /// <summary>
+    /// Expand the internal array container.
+    /// </summary>
+    /// <param name="newcapacity">The new size of the internal array - 
+    /// will be rounded upwards to a power of 2.</param>
+    /// <param name="newsize">The (new) size of the (base) collection.</param>
+    protected virtual void expand(int newcapacity, int newsize)
+    {
+      Debug.Assert(newcapacity >= newsize);
+
+      int newlength = array.Length;
+
+      while (newlength < newcapacity) newlength *= 2;
+
+      T[] newarray = new T[newlength];
+
+      Array.Copy(array, newarray, newsize);
+      array = newarray;
+    }
+
+
+    /// <summary>
+    /// Insert an item at a specific index, moving items to the right
+    /// upwards and expanding the array if necessary.
+    /// </summary>
+    /// <param name="i">The index at which to insert.</param>
+    /// <param name="item">The item to insert.</param>
+    protected virtual void insert(int i, T item)
+    {
+      if (size == array.Length)
+        expand();
+
+      if (i < size)
+        Array.Copy(array, i, array, i + 1, size - i);
+
+      array[i] = item;
+      size++;
+    }
+
+    #endregion
+
+    #region Constructors
+
+    /// <summary>
+    /// Create an empty ArrayBase object.
+    /// </summary>
+    /// <param name="capacity">The initial capacity of the internal array container.
+    /// Will be rounded upwards to the nearest power of 2 greater than or equal to 8.</param>
+    /// <param name="itemequalityComparer">The item equalityComparer to use, primarily for item equality</param>
+    protected ArrayBase(int capacity, SCG.IEqualityComparer<T> itemequalityComparer)
+      : base(itemequalityComparer)
+    {
+      int newlength = 8;
+      while (newlength < capacity) newlength *= 2;
+      array = new T[newlength];
+    }
+
+    #endregion
+
+    #region IIndexed members
+
+    /// <summary>
+    /// </summary>
+    /// <exception cref="ArgumentOutOfRangeException">If the arguments does not describe a 
+    /// valid range in the indexed collection, cf. <see cref="M:C5.CollectionBase`1.checkRange(System.Int32,System.Int32)"/>.</exception>
+    /// <value>The directed collection of items in a specific index interval.</value>
+    /// <param name="start">The low index of the interval (inclusive).</param>
+    /// <param name="count">The size of the range.</param>
+    [Tested]
+    public virtual IDirectedCollectionValue<T> this[int start, int count]
+    {
+      [Tested]
+      get
+      {
+        checkRange(start, count);
+        return new Range(this, start, count, true);
+      }
+    }
+
+    #endregion
+
+    #region IEditableCollection members
+    /// <summary>
+    /// Remove all items and reset size of internal array container.
+    /// </summary>
+    [Tested]
+    public virtual void Clear()
+    {
+      updatecheck();
+      array = new T[8];
+      size = 0;
+    }
+
+
+    /// <summary>
+    /// Create an array containing (copies) of the items of this collection in enumeration order.
+    /// </summary>
+    /// <returns>The new array</returns>
+    [Tested]
+    public override T[] ToArray()
+    {
+      T[] res = new T[size];
+
+      Array.Copy(array, offset, res, 0, size);
+      return res;
+    }
+
+
+    /// <summary>
+    /// Perform an internal consistency (invariant) test on the array base.
+    /// </summary>
+    /// <returns>True if test succeeds.</returns>
+    [Tested]
+    public virtual bool Check()
+    {
+      bool retval = true;
+
+      if (size > array.Length)
+      {
+        Console.WriteLine("Bad size ({0}) > array.Length ({1})", size, array.Length);
+        return false;
+      }
+
+      for (int i = 0; i < size; i++)
+      {
+        if ((object)(array[i]) == null)
+        {
+          Console.WriteLine("Bad element: null at index {0}", i);
+          return false;
+        }
+      }
+
+      return retval;
+    }
+
+    #endregion
+
+    #region IDirectedCollection<T> Members
+
+    /// <summary>
+    /// Create a directed collection with the same contents as this one, but 
+    /// opposite enumeration sequence.
+    /// </summary>
+    /// <returns>The mirrored collection.</returns>
+    [Tested]
+    public override IDirectedCollectionValue<T> Backwards() { return this[0, size].Backwards(); }
+
+    #endregion
+
+    /// <summary>
+    /// Choose some item of this collection. The result is the last item in the internal array,
+    /// making it efficient to remove.
+    /// </summary>
+    /// <exception cref="NoSuchItemException">if collection is empty.</exception>
+    /// <returns></returns>
+    public override T Choose() { if (size > 0) return array[size - 1]; throw new NoSuchItemException(); }
+
+    #region IEnumerable<T> Members
+    /// <summary>
+    /// Create an enumerator for this array based collection.
+    /// </summary>
+    /// <returns>The enumerator</returns>
+    [Tested]
+    public override SCG.IEnumerator<T> GetEnumerator()
+    {
+      int thestamp = stamp, theend = size + offset, thestart = offset;
+
+      for (int i = thestart; i < theend; i++)
+      {
+        modifycheck(thestamp);
+        yield return array[i];
+      }
+    }
+    #endregion
+
+    #region Range nested class
+    /// <summary>
+    /// A helper class for defining results of interval queries on array based collections.
+    /// </summary>
+    protected class Range : DirectedCollectionValueBase<T>, IDirectedCollectionValue<T>
+    {
+      int start, count, delta, stamp;
+
+      ArrayBase<T> thebase;
+
+
+      internal Range(ArrayBase<T> thebase, int start, int count, bool forwards)
+      {
+        this.thebase = thebase; stamp = thebase.stamp;
+        delta = forwards ? 1 : -1;
+        this.start = start + thebase.offset; this.count = count;
+      }
+
+      /// <summary>
+      /// 
+      /// </summary>
+      /// <exception cref="CollectionModifiedException">if underlying collection has been modified.</exception>
+      /// <value>True if this collection is empty.</value>
+      public override bool IsEmpty { get { thebase.modifycheck(stamp); return count == 0; } }
+
+
+      /// <summary>
+      /// 
+      /// </summary>
+      /// <exception cref="CollectionModifiedException">if underlying collection has been modified.</exception>
+      /// <value>The number of items in the range</value>
+      [Tested]
+      public override int Count { [Tested]get { thebase.modifycheck(stamp); return count; } }
+
+      /// <summary>
+      /// The value is symbolic indicating the type of asymptotic complexity
+      /// in terms of the size of this collection (worst-case or amortized as
+      /// relevant).
+      /// </summary>
+      /// <value>A characterization of the speed of the 
+      /// <exception cref="CollectionModifiedException">if underlying collection has been modified.</exception>
+      /// <code>Count</code> property in this collection.</value>
+      public override Speed CountSpeed { get { thebase.modifycheck(stamp); return Speed.Constant; } }
+
+      /// <summary>
+      /// Choose some item of this collection. 
+      /// </summary>
+      /// <exception cref="CollectionModifiedException">if underlying collection has been modified.</exception>
+      /// <exception cref="NoSuchItemException">if range is empty.</exception>
+      /// <returns></returns>
+      public override T Choose()
+      {
+        thebase.modifycheck(stamp);
+        if (count == 0)
+          throw new NoSuchItemException();
+        return thebase.array[start];
+      }
+
+
+      /// <summary>
+      /// Create an enumerator for this range of an array based collection.
+      /// </summary>
+      /// <exception cref="CollectionModifiedException">if underlying collection has been modified.</exception>
+      /// <returns>The enumerator</returns>
+      [Tested]
+      public override SCG.IEnumerator<T> GetEnumerator()
+      {
+        for (int i = 0; i < count; i++)
+        {
+          thebase.modifycheck(stamp);
+          yield return thebase.array[start + delta * i];
+        }
+      }
+
+
+      /// <summary>
+      /// Create a araay collection range with the same contents as this one, but 
+      /// opposite enumeration sequence.
+      /// </summary>
+      /// <exception cref="CollectionModifiedException">if underlying collection has been modified.</exception>
+      /// <returns>The mirrored collection.</returns>
+      [Tested]
+      public override IDirectedCollectionValue<T> Backwards()
+      {
+        thebase.modifycheck(stamp);
+
+        Range res = (Range)MemberwiseClone();
+
+        res.delta = -delta;
+        res.start = start + (count - 1) * delta;
+        return res;
+      }
+
+
+      IDirectedEnumerable<T> C5.IDirectedEnumerable<T>.Backwards()
+      {
+        return Backwards();
+      }
+
+
+      /// <summary>
+      /// <code>Forwards</code> if same, else <code>Backwards</code>
+      /// </summary>
+      /// <exception cref="CollectionModifiedException">if underlying collection has been modified.</exception>
+      /// <value>The enumeration direction relative to the original collection.</value>
+      [Tested]
+      public override EnumerationDirection Direction
+      {
+        [Tested]
+        get
+        {
+          thebase.modifycheck(stamp);
+          return delta > 0 ? EnumerationDirection.Forwards : EnumerationDirection.Backwards;
+        }
+      }
+    }
+    #endregion
+  }
+}