Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Steve 472 posts 1216 karma points
    May 02, 2014 @ 15:52
    Steve
    0

    Better Syntax?

    I have a foreach with multiple conditions and it just seems like a bloated way to do the tests. Is there a shorter way to write this? We are using 4.11 and will be switching to ver 6 in a few months.

    @foreach (var node in page.Children.Where("Visible && NodeTypeAlias == \"Category2InternalPage\" || NodeTypeAlias == \"ExternalLink\" || NodeTypeAlias == \"StudentGroupsPage\""))
  • Jeavon Leopold 3074 posts 13632 karma points MVP 11x admin c-trib
    May 02, 2014 @ 16:12
    Jeavon Leopold
    1

    Hi Steve,

    You can do this:

    @foreach (var node in page.Children.Where("Visible && NodeTypeAlias == @0 || NodeTypeAlias == @1 || NodeTypeAlias == @2", "Category2InternalPage", "ExternalLink", "StudentGroupsPage"))
    

    If you are using the legacy Razor Macros you maybe be able to use the .ContainsAny method, this will also be available in v6.2 and v7.1.2 when using MVC (see here)

    It would be something like this (untested):

    var keywords = new List<string> {"Category2InternalPage", "ExternalLink", "StudentGroupsPage"};
    @foreach (var node in page.Children.Where("Visible && NodeTypeAlias.ContainsAny(@0)", keywords))
    

    Jeavon

  • Steve 472 posts 1216 karma points
    May 02, 2014 @ 17:27
    Steve
    0

    Thanks Jeavon! This is great! Is the @1 Razors way of doing C# placeholders? {0}

    ("Visible && NodeTypeAlias == @0 || NodeTypeAlias == @1 || NodeTypeAlias == @2","Category2InternalPage","ExternalLink","StudentGroupsPage"))
Please Sign in or register to post replies

Write your reply to:

Draft