Auston Lopez
Auston Lopez

Reputation: 29

.split with razor details C# asp.net core

Want to take the string NPCSkills and have it split into a list

NPCSkills is a prop that includes a string like "guns = 4, armor = 2" I want it to split into a list so I can display it

  • item 1
  • item 2
  • I am doing the .split but not sure what to do now.

     string[] Words = (Model.NPCSkills).Split(',');
     foreach (var item in Words)
     {
         <li>
         @item.Words
         </li>
     }
    

    string does not contain a definition for 'Words' and no extension method 'Words' accepting a first argument of type string could be found (are you missing a using directive or an assembly reference?) + @item.Words

    Upvotes: 0

    Views: 936

    Answers (1)

    itminus
    itminus

    Reputation: 25360

    You could use the following code to convert the NPCSkills(comma-separated string) to a strongly-typed Dictionary:

    var Words = (Model.NPCSkills)
        .Split(',')
        .Select(s => s.Split("="))
        .ToDictionary(arr => arr[0], arr =>arr[1] );
    

    Or if you would like to remove the space around the key/value pair :

    var Words = (Model.NPCSkills)
        .Split(',')
        .Select(s => s.Split("=").Select(e => e.Trim()).ToArray())
        .ToDictionary(arr => arr[0], arr =>arr[1]);
    

    Now you could render it in a safer way:

    @foreach(var item in Words)
    {
        <li>
            <span class="badge">@item.Key</span>
            <span class="text">@item.Value</span>
        </li>
    }
    

    Upvotes: 1

    Related Questions