I find it difficult to understand the following C # code. This code was taken from Pro ASP.NET MVC 2 Framework by Stephen Sanderson. This code generates URLs based on a list of categories.
Here is 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)
There are a lot of things. I assume that it defines a function that expects two type string parameters and NavLink. Then I see Lambda categoryName => new NavLink etc.... I think all he does is create an instance NavLink.
Then the function is called in the same controller action:
List<NavLink> navLinks = new List<NavLink>();
navLinks.Add(makeLink(null));
var categories = productsRepository.Products.Select(x => x.Category.Name);
foreach (string categoryName in categories.Distinct().OrderBy(x => x))
navLinks.Add(makeLink(categoryName));
I can say that he is making a NavLink list. I don’t understand why Stephen Sanderson wrote it like this. Could he write 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 any advantage to doing this Stephen against my path?