Why did they use this C # syntax to create a list of links in ASP.NET MVC 2?

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:

        // 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 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?

+5
5

, , , . , , .

+5

, , , -, . - , ...

: , " " , , ...

+2

, , NavLink.

NavLink.

, , - NavLinks . - , , .

+1

. , .

: (1) (2) - , .

+1
source

(this is just an opinion not intended to insult or provoke)

Personally, I like your way better. (or a model where you just write a plain old private function called internally by foreach).

It is fashionable to do something with a lambda, but in this case you won nothing (no delayed execution). In this case, I think lambda just makes the code much less clear.

+1
source

All Articles