我有以下助手来检查字典键是否存在。这适用于字符串字符串类型字典
var myDictionary = new Dictionary<string, string>();
myDictionary.GetValue("FirstName");
public static TU GetValue<T, TU>(this Dictionary<T, TU> dict, T key) where TU : class
{
TU val;
dict.TryGetValue(key, out val);
return val;
}
如何重构它,以便如果我有一个带有列表的字典,我想检查键是否存在,如果存在,则获取列表中的第一项,例如:
var myDictionary = new Dictionary<string, List<string>>();
//populate the dictionary...
// Call to get first item from dictionary using key
myDictionary.GetValue("FirstName")[0]
我想在剃须刀中使用它,如下所示:
<span >@myDictionary.GetValue("FirstName")[0]</span>
您对错误消息原因的假设不正确:问题不在于您从GetValue
返回List<string>
,问题在于您正在尝试索引找不到键时返回的 null 值。
您需要验证结果是否为空:
<span>@(myDictionary.GetValue("FirstName") != null ? myDictionary.GetValue("FirstName")[0] : null)</span>
在这种情况下,原始函数似乎更有用:
<span>@(myDictionary.TryGetValue("FirstName", out var val) ? val[0] : null)</span>
您可以修改函数以返回空集合,但随后会出现索引超出范围错误。我没有看到合理的返回对象允许您按任意值进行索引而不会出错。否则,您必须创建第二个函数来处理可索引类型,这将您引向另一个答案(我看到该答案已被删除,因此放在这里):
public static TU GetFirstValue<T, TU>(this Dictionary<T, IEnumerable<TU>> dict, T key) {
IEnumerable<TU> val;
dict.TryGetValue(key, out val);
return (val == null ? default(TU) : val.First());
}
您也可以将原始函数重命名为 GetFirstValue,编译器将使用合适的函数。