Filter and sort pages in as few lines as possible
An example of a couple of useful lambda expressions. At least I think so. These lines are used on a typical A-Z index page, and use a HTTP parameter (line 2) to filter the pages. On line 3 it uses a gorgious lambda to sort by page name.
Can it be done shorter or more beautiful, I wonder? :)
1: List<PageData> pages = new List<PageData>(GetChildren(CurrentPage.PageLink));
2: pages.RemoveAll(page => !page.PageName.ToUpper().StartsWith(Request["c"].ToUpper()));
3: pages.Sort((p1, p2) => p1.PageName.CompareTo(p2.PageName));
4:
5: // plDictionary is a PageList. Contains all pages with a page name starting with
6: // the string Request["c"].
7: plDictionary.DataSource = pages;
8: plDictionary.DataBind();
plDictionary.DataSource = GetChildren(CurrentPage.PageLink)
.AsEnumerable()
.Where(pd => string.Compare(pd.PageName, Request["c"], true) == 0)
.OrderBy(pd => pd.PageName);
/ Aanund Austrheim
Woops, wrong Where clause, just wrote it like I usually do:P Just switch it.
Yes, that was undoubtedly awesome :)
Extensions + lambda rocks!
Great stuff! Straight into the favourites :)
/ Martin Söderlund