如何从Dictionary>指定键的整型值

本文关键字:char 整型 Tuple Dictionary int | 更新日期: 2023-09-27 18:17:37

我有两个字典第一种情况下,我使用Tuple作为键值它像这样工作得很好

Dictionary<Tuple<char, char>, int> pairPoints = new Dictionary<Tuple<char, char>, int>();
foreach (var items in this.pairPoints)
   Console.WriteLine(items.Key.Item1);

但在第二种情况下,我想得到一个值也在Tuple {int,char}但是我找不到像result。values。item1

Dictionary<char, Tuple <int, char>> result = new Dictionary<char, Tuple<int, char>>();
if(distance < result.Values.Item1) {//do my things}

是否可以这样写,或者我必须使用不同的数组方法?

如何从Dictionary<char, Tuple <int, char>>指定键的整型值

result.ValuesTuple<int, char>集合您可以通过字典键

访问集合中的单个项。
result[someChar].Item1

或者您可以像下面这样循环遍历所有的值:

foreach(var tuple in result.Values)
    Console.WriteLine(tuple.Item1)

您有多种方法可以做到这一点。但是您需要首先了解result.Values是一个集合,而不是单个值,这就是为什么您不能访问result.Values.Item1

检查是否有匹配的结果:

if(result.Values.Any(t => t.Item1 > distance))
{
}

Or循环匹配

的结果
foreach(var item in result.Values.Where(t => t.Item1 > distance))
{
  // use item.Item1 and item.Item2
}

你的做法不对。你必须使用Value而不是Values

正确的方法:

Dictionary<char, Tuple <int, char>> result = new Dictionary<char, Tuple<int, char>>();
    foreach (var items in result)
    {
        Console.WriteLine(items.Value.Item1);
        Console.WriteLine(items.Value.Item2);
    }