You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何一行代码检查Dictionary<int, KeyValuePair<string, int>>中是否存在指定字符串?

解决方案

一行代码实现(LINQ)

直接用LINQ的Any()方法就能完成,无需显式编写for/foreach循环:

bool hasTargetString = myDictionary.Values.Any(val => val.Key == "你要找的字符串");

原理是Values属性返回字典中所有KeyValuePair<string, int>的集合,Any()会内部遍历这个集合(不用你手写循环),只要找到任意一个元素的Key匹配目标字符串,就返回true,否则返回false。

其他优化方案

如果需要频繁执行这类检查,每次用Any()遍历的效率可能不够理想,建议额外维护一个HashSet<string>同步记录字典中存在的字符串:

// 初始化两个集合
Dictionary<int, KeyValuePair<string, int>> myDict = new();
HashSet<string> existingStrings = new();

// 添加元素时同步更新
void AddElement(int dictKey, string targetStr, int pairedInt)
{
    myDict.Add(dictKey, new KeyValuePair<string, int>(targetStr, pairedInt));
    existingStrings.Add(targetStr);
}

// 检查时直接O(1)复杂度完成
bool hasTarget = existingStrings.Contains("你要找的字符串");

这种方式把检查操作的时间复杂度从O(n)降到了O(1),适合高频查询的场景。

内容的提问来源于stack exchange,提问作者polelord

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 11:38:10