C#-重构字典助手

C#-重构字典助手,c#,dictionary,refactoring,C#,Dictionary,Refactoring,我有下面的助手来检查字典键是否存在。这适用于字符串类型字典 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.T

我有下面的助手来检查字典键是否存在。这适用于字符串类型字典

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=newdictionary();
myDictionary.GetValue(“名字”);
公共静态TU GetValue(此字典dict dict,T键),其中TU:class
{
图瓦尔;
dict.TryGetValue(键,输出值);
返回val;
}
我如何重构它,以便如果我有一个带有列表的字典,我想检查键是否存在,以及它是否存在,以获取列表中的第一项,例如:

var myDictionary = new Dictionary<string, List<string>>();

//populate the dictionary...

// Call to get first item from dictionary using key
myDictionary.GetValue("FirstName")[0]
var myDictionary=newdictionary();
//填充字典。。。
//调用以使用键从字典中获取第一项
myDictionary.GetValue(“名字”)[0]
我想在razor中使用它,如下所示:

  <span >@myDictionary.GetValue("FirstName")[0]</span>
@myDictionary.GetValue(“FirstName”)[0]

您对错误消息原因的假设是不正确的:问题不是您正在从
GetValue
返回
列表,问题是您正在尝试索引未找到键时返回的空值

您需要验证您的结果是否不为空:

<span>@(myDictionary.GetValue("FirstName") != null ? myDictionary.GetValue("FirstName")[0] : null)</span>
@(myDictionary.GetValue(“FirstName”)!=null?myDictionary.GetValue(“FirstName”)[0]:null)
在这种情况下,原始函数似乎更有用:

<span>@(myDictionary.TryGetValue("FirstName", out var val) ? val[0] : null)</span>
@(myDictionary.TryGetValue(“FirstName”,out var val)?val[0]:null)
您可以修改函数以返回空集合,但随后会出现索引超出范围错误。我认为没有任何合理的返回对象允许您按任意值进行索引而不会出错。否则,您必须创建第二个函数来处理可索引类型,这将引导您找到另一个答案(我看到该答案已被删除,所以放在这里):

publicstatictugetfirstvalue(这个字典dict,T键){
可数val;
dict.TryGetValue(键,输出值);
返回值(val==null?默认值(TU):val.First());
}

您也可以将原始函数重命名为GetFirstValue,编译器将使用任何合适的函数。

它已经执行了您希望它执行的操作。@Servy no如果键不存在,它会引发异常,因为值类型是一个列表。您说如果键有值,它应该将其提供给您,并且没有提到如果没有值它应该做什么,所以再次强调,您提供的代码已经完成了您所说的它需要做的事情。只要调用myDictionary.GetValue(“FirstName”).FirstOrDefault(),当您知道您正在处理的字典每个键都有可枚举的值时,或者根据Sergey的回答写一个单独的扩展方法。我认为在同一个函数中处理可枚举和非可枚举并不是一种真正明智的方法,当然,在不知道将可枚举中的各个对象强制转换为什么的情况下也是如此。@Servy有什么不正常的地方吗?我不知道。如果有些东西不正常,我会说,“字典不是”正常的键值类型字典“
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());
}