The SPWebCollection returned by the member SPWeb.Webs is a not sorted list of SPWeb objects. So i wrote a class which makes it possible to return a sorted list of SPWeb objects based on the property of a SPWeb. It is basically very simple and uses some standard .NET interfaces for enumerating and comparing.
public class SPSortedWebCollection : IEnumerable, IEnumerator
{
private ArrayList list = new ArrayList();
private int index = -1;
private string property = "";
The constructor of the class needs a name of the property and the original collection of SPWeb objects returned by for example the SPWeb.Webs member. It adds the SPWeb objects and initializes the class.
public SPSortedWebCollection(SPWebCollection webs, string property)
{
this.property = property;
foreach(SPWeb child in webs)
{
Add(child);
}
Reset();
}
This method can be used to add some additional SPWeb objects. Don't forget to call the Reset() member for resetting and sorting the collection again.
public void Add(SPWeb web)
{
list.Add(new SPSortedWeb(web, property));
}
Inside the class another class is found which stores the SPWeb objects. It uses the IComparable interface for comparing itself against another instance of SPSortedWeb. The Sort member of the ArrayList automatically uses the CompareTo member of the interface when sorting the list.
protected class SPSortedWeb : IComparable
{
private SPWeb web = null;
private string property = "";
public SPSortedWeb(SPWeb web, string property)
{
this.web = web;
this.property = property;
}
public SPWeb Web
{
get
{
return web;
}
}
public int CompareTo(object obj)
{
SPSortedWeb sw = obj as SPSortedWeb;
string val = SharePointHelper.GetPropertyCode(web, property);
string compareToVal = SharePointHelper.GetPropertyCode(sw.Web, property);
return val.CompareTo(compareToVal);
}
}
Finally the class is given some methods for enumerating through the list. You can use easily the foreach(...) loop to retrieve the SPWeb objects.
public IEnumerator GetEnumerator()
{
return this;
}
public void Reset()
{
list.Sort();
index = -1;
}
public object Current
{
get
{
SPSortedWeb sw = (index < 0 || index >= list.Count) ? null : list[index] as SPSortedWeb;
return sw != null ? sw.Web : null;
}
}
public bool MoveNext()
{
index++;
return index < list.Count;
}
}
For retrieving the property of a SPWeb object the following class is used:
public class SharePointHelper
{
public static string GetPropertyCode(SPWeb web, string property)
{
if (web.Properties.ContainsKey(property))
{
return web.Properties[property];
}
return "";
}
}
To use the class the following example gives you some idea of how it works:
SPSortedWebCollection col = new SPSortedWebCollection(currentWeb.Webs, "Number");
foreach(SPWeb child in col)
{
...
}