简体   繁体   English

要简化键为元组时对字典的C#访问

[英]Want to Simplify C# Access to Dictionary When Key is Tuple

Is there a simpler way to check a dictionary where the key is a tuple and then assign the value you were just checking for to a variable? 有没有更简单的方法来检查键为元组的字典,然后将您刚刚检查的值分配给变量? I've got the following code that works, but it seems tedious. 我有以下有效的代码,但似乎很乏味。

int hitCount = dict.ContainsKey(new Tuple<string, string>(tr, "H"))
   ? dict[new Tuple<string, string>(tr, "H")]
   : 0;
int hitCount;
var key = new Tuple<string, string>(tr, "H");
dict.TryGetValue(key, out hitCount);

Starting with C# 7: 从C#7开始:

var key = new Tuple<string, string>(tr, "H");
dict.TryGetValue(key, out int hitCount);

The difference is that the declaration of hitCount is moved to the place where it's used as an out parameter. 区别在于hitCount的声明被移至用作out参数的位置。

It's obviously not really necessary to define the key in a separate variable, but in these scenarios you're likely going to want to add the key if it doesn't exist. 显然没有必要在单独的变量中定义键,但是在这些情况下,如果键不存在,则可能需要添加键。

Use Tuple.Create to let the compiler infer generic type parameters from the type of method arguments: 使用Tuple.Create使编译器从方法参数的类型推断通用类型参数:

int hitCount;
if (!dict.TryGetValue(Tuple.Create(tr, "H"), out hitCount)) {
    hitCount = 0;
}

Note: Setting hitCount to zero is not necessary. 注意: hitCounthitCount设置为零。 This code illustrates how to deal with missing keys, in case you wish to use a different number as a default. 该代码说明了在您希望使用其他数字作为默认值的情况下如何处理丢失的密钥。

Use Dictionary<K,V>.TryGetValue : 使用Dictionary<K,V>.TryGetValue

int hitCount;
dict.TryGetValue(new Tuple<string, string>(tr, "H"), out hitCount);

If the value is not found, hitCount will be assigned to int 's default value, that is 0 . 如果找不到该值,则hitCount将分配给int的默认值0

In the off-chance this might help others, with C# 7.0 you can declare and even name the fields in your tuple, and easily retrieve those values for logging or other manipulation. 在不大可能的情况下,这可能会对其他人有所帮助,使用C#7.0,您可以声明甚至命名元组中的字段,并轻松检索这些值以进行日志记录或其他操作。

var tupleKey = (FirstParam: tr, SecondParam: "H");

if (dict.ContainsKey(tupleKey))
{
     _logger.Log($"Found key using {tupleKey.FirstParam} and {tupleKey.SecondParam}.");
     return dict[tupleKey];
}
return 0;

Or for quick recall: 或快速召回:

dict.TryGetValue(tupleKey, out int hitCount);

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

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