繁体   English   中英

KeyValuePair的投放问题

[英]Casting issue with KeyValuePair

我有一个要搜索的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;

以及我该如何解决?

使用Where获取集合,而不是单个结果。 使用FirstFirstOrDefaultSingleSingleOrDefault代替:

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

要从字典中获取结果,您应该使用

cOperationInstanceNameLookup[pOperationInstanceName]

并测试字典是否包含您的密钥

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM