Views: 2577
Number of votes: 0
Average rating:

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();
Sep 08, 2009

Guest
(By Guest, 9/21/2010 12:32:38 PM)

plDictionary.DataSource = GetChildren(CurrentPage.PageLink)
.AsEnumerable()
.Where(pd => string.Compare(pd.PageName, Request["c"], true) == 0)
.OrderBy(pd => pd.PageName);

/ Aanund Austrheim

Aanund Austrheim
(By Aanund Austrheim, 9/21/2010 12:32:38 PM)

Woops, wrong Where clause, just wrote it like I usually do:P Just switch it.

thomas
(By thomas, 9/21/2010 12:32:38 PM)

Yes, that was undoubtedly awesome :)

Magnus Rahl
(By Magnus Rahl, 9/21/2010 12:32:38 PM)

Extensions + lambda rocks!

Guest
(By Guest, 9/21/2010 12:32:38 PM)

Great stuff! Straight into the favourites :)
/ Martin Söderlund

Please login to comment.