asp.net mvc - a default value for a Dictionary in c# -


i have following pageviewmodel class:

public class pageviewmodel : viewmodel<page> {  public pageviewmodel ()         {             kywords = new list<keyword>();             answserkeyworddictionary = new dictionary<string, answer>();         }         public company company { get; set; }         public list<keyword> kywords { get; set; }         public dictionary<string, answer> answserkeyworddictionary { get; set; } } 

in view i'm using property answserkeyworddictionary that:

@html.displayaffirmativeanswer(model.answserkeyworddictionary["mykey"]) 

my question : how can return default value if "mykey" not in dictionary.

thanks in advance

check if exists, if not, return default value:

model.answserkeyworddictionary.containskey("mykey")     ? model.answserkeyworddictionary["mykey"]     : "default" 

you create extension method that:

    public static dictionary<k, v> getvalueordefault<k, v>(this dictionary<k, v> dictionary, k key, v defaultvalue)     {         v val;         if (dictionary.trygetvalue(key, out val))         {             return val ?? defaultvalue;         }          return defaultvalue;     } 

use this:

model.answserkeyworddictionary.getvalueordefault("mykey", "default") 

Comments

Popular posts from this blog

php - Submit Form Data without Reloading page -

linux - Rails running on virtual machine in Windows -

php - $params->set Array between square bracket -