c#中字典的默认值

时间:2014-09-19 13:27:21

标签: c# asp.net-mvc dictionary

我有以下PageViewModel类:

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; }
}

在我看来,我正在使用属性AnswserKeywordDictionary:

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

我的问题是:如果&#34; myKey&#34;我怎么能返回默认值?不在字典里。

提前致谢

2 个答案:

答案 0 :(得分:3)

检查是否存在,如果不存在,则返回默认值:

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

您还可以为此创建扩展方法:

    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;
    }

像这样使用:

Model.AnswserKeywordDictionary.GetValueOrDefault("myKey", "default")

答案 1 :(得分:0)

使用方法抽象你的字典:

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

然后在您的视图中使用该方法:

@Html.DisplayAffirmativeAnswer(Model.GetAnswer("myKey"))