1

I have the 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 my view i'm using the property AnswserKeywordDictionary like that:

@Html.DisplayAffirmativeAnswer(Model.AnswserKeywordDictionary["myKey"])

my question is : how can i return a default value if "myKey" is not in the dictionary.

Thanks in advance

Bilel Chaouadi
  • 903
  • 1
  • 10
  • 28

2 Answers2

5

Check if it exists, if not, return a default value:

Model.AnswserKeywordDictionary.ContainsKey("myKey")
    ? Model.AnswserKeywordDictionary["myKey"]
    : "default"

You could also create an extension method for 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 it like this:

Model.AnswserKeywordDictionary.GetValueOrDefault("myKey", "default")
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
0

Abstract your dictionary with a method:

public Dictionary<string, Answer> AnswserKeywordDictionary { get; set; }
public GetAnswer(string key, Answer defaultValue)
{
   if(AnswserKeywordDictionary.ContainsKey(key)
       return AnswserKeywordDictionary[key];
   return defaultValue;
}

then use that method in your View:

@Html.DisplayAffirmativeAnswer(Model.GetAnswer("myKey"))
D Stanley
  • 149,601
  • 11
  • 178
  • 240