I'm having hard time understanding the following C# code. This code was taken from Pro ASP.NET MVC 2 Framework by Steven Sanderson. The code esentially creates URLs based on a list of categories.
Here's the code:
Func<string, NavLink> makeLink = categoryName => new NavLink {
Text = categoryName ?? "Home",
RouteValues = new RouteValueDictionary(new {
controller = "Products",
action = "List",
category = categoryName,
page = 1
}),
IsSelected = (categoryName == currentCategory)
A lot of stuff is going on here. I'm guessing it's defining a function that expects two parameters of type string, and NavLink. Then I see the Lambda categoryName => new NavLink etc...
. I think all it's doing is creating an instance of NavLink
.
The function is then called in the same Controller action:
// Place home link on top
List<NavLink> navLinks = new List<NavLink>();
navLinks.Add(makeLink(null));
// Add link for each distinct category
var categories = productsRepository.Products.Select(x => x.Category.Name);
foreach (string categoryName in categories.Distinct().OrderBy(x => x))
navLinks.Add(makeLink(categoryName));
I can tell that it's making a list of NavLink. I don't understand why Steven Sanderson wrote it this way though. Couldn't he have written something like:
var categories = productsRepository.Products.Select(x => x.Category.Name);
foreach (string categoryName in categories.Distinct().OrderBy(x => x))
{
var newlink = new Navlink{
text = categoryName,
RouteValues = new RouteValueDictionary(new {
controller = "Products",
action = "List",
category = categoryName,
page = 1
}),
IsSelected = (categoryName == currentCategory)
}
navLinks.Add(newlink);
}
Is there an advantage to doing it Steven's way versus my way?