我有一个KeyValuePair列表,我想搜索一下。我用这种方式编写的搜索功能:
public KeyValuePair<string, OperationInstance> operationInstanceLookupByName(string pOperationInstanceName)
{
KeyValuePair<string, OperationInstance> lResultOperationInstance = new KeyValuePair<string,OperationInstance>();
try
{
var result = cOperationInstanceNameLookup.Where(kvp => kvp.Key == pOperationInstanceName);
if (result.Count() != 0)
lResultOperationInstance = result;
else
cOutputHandler.printMessageToConsole("Operation Instance " + pOperationInstanceName + " not found in Dictionary!");
}
catch (Exception ex)
这项任务有什么问题:
lResultOperationInstance = result;
我该如何解决?
答案 0 :(得分:2)
使用Where
您将获得一个集合而不是一个结果。请改用First
或FirstOrDefault
或Single
或SingleOrDefault
:
var result = cOperationInstanceNameLookup.SingleOrDefault(kvp => kvp.Key == pOperationInstanceName);
if (result != null)
...
.FirstOrDefault will return the first matching item or null if not found.
.SingleOrDefault will return the matching item if there is only one, or null if there isn't or an exception if there are multiple.
然而,更好的方法是使用字典按预期获取实例。
以下内容将从字典中找到该项,但如果不存在则会抛出异常:
OperationInstance result = cOperationInstanceNameLookup[pOperationInstanceName];
您可以先使用.ContainsKey对其进行测试,但以下方法会尝试获取该值并允许您同时检查它是否存在。这是最快的方法:
OperationInstance result = null;
if (cOperationInstanceNameLookup.TryGetValue(pOperationInstanceName, out result))
// result will be populated
else
// result is still null
答案 1 :(得分:0)
要从您的词典中获取结果,您应该使用
cOperationInstanceNameLookup[pOperationInstanceName]
并测试dictionnary是否包含您的密钥
cOperationInstanceNameLookup.ContainsKey(pOperationInstanceName)
你会有更好的表现!
所以这样的事情应该可以解决问题(感谢@juharr):
public KeyValuePair<string, OperationInstance> operationInstanceLookupByName(string pOperationInstanceName)
{
KeyValuePair<string, OperationInstance> lResultOperationInstance =
new KeyValuePair<string, OperationInstance>();
OperationInstance value;
if (cOperationInstanceNameLookup.TryGetValue(pOperationInstanceName, out value))
lResultOperationInstance = new KeyValuePair<string, OperationInstance>(pOperationInstanceName, value);
else
cOutputHandler.printMessageToConsole("Operation Instance " + pOperationInstanceName + " not found in Dictionary!");
return lResultOperationInstance;
}