This project has moved and is read-only. For the latest updates, please go here.

OrderedCollection<T>

NuGet Package ID: CodeBits.OrderedCollection

An OrderedCollection is a collection whose items are always sorted.
Adding new items will always insert the item at the correct sort location, instead of simply adding it to the end of the collection.

Ordered collections have the following properties to determine their behavior:
  • AllowDuplicates (bool): Specifies whether to allow duplicate values to be inserted. Defaults to false.
  • ReverseOrder (bool): Specifies whether to sort the collection in reverse order. Defaults to false.

The following rules govern the sorting logic of the collection:
  1. You can pass an IComparer<T> instance in a constructor, and this will used to compare items while sorting.
  2. You can pass a Comparer<T> delegate in a constructor, and this will be used to compare items while sorting
  3. If neither an IComparer<T> instance nor a Comparison<T> delegate is passed, the collection will attempt to use the type's IComparable<T> implementation, if available. If an IComparable<> implementation is not found on the type, an exception is thrown.
  4. If using a derived class, you can override the protected Compare method to define your own custom comparison logic that will override the above 3 behaviors.

Initializing an OrderedCollection<T> using it's constructors:
// Use a IComparer to do a case-insensitive string comparison
var items = new OrderedCollection<string>(StringComparer.OrdinalIgnoreCase);

// Use a Comparison delegate to compare based on string lengths
Comparison<string> logic = (x, y) => x.Length - y.Length;
var items = new OrderedCollection<string>(logic);

// Uses the string type's IComparable<> implementation to do comparisons
var items = new OrderedCollection<string>();

Overriding the Compare method to provide custom sorting logic in a derived class:
public class MyOrderedCollection : OrderedCollection<string>
{
    // Compares strings based on length and not value
    protected override int Compare(string x, string y)
    {
        return x.Length - y.Length;
    }
}

Last edited Jul 10, 2012 at 11:36 PM by jeevanjj, version 6

Comments

No comments yet.