asp.net mvc - a default value for a Dictionary in c# -
this question has answer here:
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
Post a Comment