(Migrated post from June 18th, 2007)
Since working in a .NET 1.1. object model, I wanted to implement my own strong typed collection. Since I am a rather lazy person I simply inherited from System.Collections.Specialized.NameObjectCollectionBase and just roughly implemented the most needed methods.
The szenario: My collection should hold a collection of SPRemoteObject's (I'm working on a web-service based SharePoint project - obviously).
An SPRemoteObject is a base class that just holds some common properties like Name, Url, Type etc.
Implementeing NameObjectCollectionBase is a piece of cake. Just when finishing my prototype, it came to me, that all SPRemoteObjects should also be sorted (most SP-Objects come already sorted - but as always with SharePoint, there are some exceptions).
How to implement a pragmatic sort now in this collection? I searched the web but haven't found a true help there. Either the topic is too easy and I don't get it, nobody uses this class in the age of Generocs anymore or there is simply no straight forward solution published for this.
Anyway, this is how I did it and it works really perfectly:
1. In your object (here SPRemoteObject), implement IComparable. This is in my case straight-forward, since I want to sort by name:
public int CompareTo(object obj)
{
if (obj is SPRemoteObject)
return this.Name.CompareTo(((SPRemoteObject)obj).Name);
return 0;
}
#endregion
2. In the collection, implement the following simple method:
public void Sort()
{
ArrayList arrayList = new ArrayList(this.AllValues);
arrayList.Sort();
this.Clear();
this.AddRange((SPRemoteObject[])arrayList.ToArray(typeof(SPRemoteObject)));
arrayList = null;
}
Maybe not perfect in terms of performance, but it works!