代码之家  ›  专栏  ›  技术社区  ›  polelord

是否有任何方法可以检查KeyValuePair<string,int>是否在字典中的一行中包含特定的Key?

  •  -1
  • polelord  · 技术社区  · 1 年前

    在我的代码中,我有一个字典,起初它只是<字符串,int>。然而,我需要一种方法,让具有相同字符串的两个东西在Dictionary中成为独立的元素,所以我将Key int和Value设置为KeyValuePair<字符串,int>。

    Dictionary<int, KeyValuePair<string, int>>()

    问题是,我需要检查字典中是否存在特定的字符串, 优选不使用for/foreach循环 .使用词典。ContainsValue我可以检查KeyValuePair,但KeyValuePaire中的int没有指定,如果我使用ContainsValue,则需要指定。

    是否有任何方法可以检查字典是否包含一行中具有特定密钥的KeyValuePair?

    如果有人能为这个问题找到其他解决方案,那也太好了。

    提前感谢!

    2 回复  |  直到 1 年前
        1
  •  1
  •   Steve Py    1 年前

    +1 Dictionary看起来不再是满足您需求的适当数据结构。您已经从需要一个唯一的字符串(本质上是索引值)变成了一个可以复制字符串的结构。你可以很容易地使用 List<KeyValuePair<string,int>> 现在

    但是,是的,您仍然可以检查字典的值:

    // Does a string exist: 
    var exists = myDictionary.Values.Any(x => x.Key == myString);
    
    // Values with string: 
    var keyValues = myDictionary.Values.Where(x => x.Key == myString);
    

    除非您仍然有根据唯一ID为字典编制索引的代码,否则继续使用字典是没有意义的。

        2
  •  0
  •   Gerry Schmitz    1 年前

    听起来你想要一本字典;这(我发现)在团队和多人场景中经常出现;例如

    // ... playerDic = new Dictionary<int, Dictionary<string, int>>();
    // ... propertyDic = new Dictionary<string, int>();
    
    int player = 1;
    string property = "Lives";
    
    propertyDic[ property ] = 9;
    playerDic[ player ] = propertyDic;
    
    // ...
    var playerLives = playerDic.Contains( player ) ? 
       playerDic[ player ].Contains( property ) ?
       playerDic[ player ][ property ] : 0;  // or some other default.
    

    通常情况下,你会用播放器“初始化”这些字典(在启动和连接时),所以你不需要每次都进行“包含播放器”检查。