A questioner posed an interesting question on SharePoint StackExchange – how to get all the web sites (SPWeb) in SharePoint and sort them alphabetically.
SPSite.AllWebs returns a collection of all web sites that are contained within the site collection. But they seem to be in random order and are not sorted alphabetically based on their Title. Sorting these web sites based on their title is actually pretty easy.
SPSite.AllWebs returns object of SPWebCollection which inherits from IEnumerable<T> interface. This interface has a function called OrderBy using which we can order the SPWeb based on its Title property.
You also need to make sure that you use the following namespaces otherwise it will throw error.
You can extend the above code snippet to sort based on Description and other properties of SPWeb also.
SPSite.AllWebs returns a collection of all web sites that are contained within the site collection. But they seem to be in random order and are not sorted alphabetically based on their Title. Sorting these web sites based on their title is actually pretty easy.
SPSite.AllWebs returns object of SPWebCollection which inherits from IEnumerable<T> interface. This interface has a function called OrderBy using which we can order the SPWeb based on its Title property.
SPWebCollection webColl = site.AllWebs; // Sort the SPWeb alphabetically based on Title IEnumerablesortWebColl = webColl.OrderBy(w => w.Title); foreach (SPWeb web in sortWebColl) { // Code }
You also need to make sure that you use the following namespaces otherwise it will throw error.
using System.Linq; using System.Collections; using System.Collections.Generic;
You can extend the above code snippet to sort based on Description and other properties of SPWeb also.