SharePoint 2013 C# get all websites and sort alphabetically
-
04-10-2020 - |
Question
I am currently building a visual webpart for an on premise SharePoint farm in C#.
I am currently able to get all of the webs and also get all of the list items within each web, using the CAML Query I am also able to sort the list items alphabetically but I am however unable to sort the webs.
The application currently returns the web.title
but in any order, it is a requirement to have this sorted alphabetically. This is how the code currently looks:
using(SPSite site = new SPSite(siteUrl)) {
foreach(SPWeb web in site.AllWebs) {
try {
using(SPWeb webList = site.OpenWeb(web.Url.Substring(siteUrl.Length))) {
//check if our list exists wherever we are currently
SPList list = webList.Lists.TryGetList("Faqs");
if (list != null) {
rv += "<h3><a onclick=\"toggle_visibility('" + web.ID + "');\">" + web.Title + "</a><span onclick=\"toggle_visibility('" + web.ID + "');\"></span></h3>";
rv += "<div>";
rv += "<ul id=\"" + web.ID + "\" style=\"display:none;\">";
SPQuery query = new SPQuery();
query.Query = "<OrderBy><FieldRef Name='Title' Ascending='TRUE' /></OrderBy>";
foreach(SPListItem item in list.GetItems(query)) {
rv += "<li>";
rv += "<a href=\"" + web.Url + "/Pages/page.aspx>\n\r";
rv += item["something"].ToString() + "<br />";
rv += "</a>\r\n";
rv += "</li>\r\n";
}
rv += "</ul>";
rv += "</div>";
}
}
}
}
}
I basically want to sort by the web.title
I have tried JavaScript but so far not had any luck.
Any help is greatly appreciated.
Solution
The property site.AllWebs
returns an object of SPWebCollection
which inherits from IEnumerable<T>
interface. This interface has a function called OrderBy
using which you can order the SPWeb
based on their Title
property.
SPWebCollection webColl = site.AllWebs;
IEnumerable<SPWeb> sortWebColl = webColl.OrderBy(w => w.Title);
foreach (SPWeb web in sortWebColl) {
// Code
}
Make sure you use the following namespaces otherwise it will throw error.
using System.Linq;
using System.Collections;
using System.Collections.Generic;