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

C# 如何判断指定值存在于符合键格式规则的Dictionary<string,string>中

实现方法

核心逻辑是先校验字典键的格式合规性,再匹配入参条件,最终判断目标值是否存在,步骤如下:

  • 遍历字典所有键值对,先按::分隔符拆分键,严格校验必须为非空id、schema名、列名组成的三段结构,不符合格式的键直接跳过
  • 对格式合规的键,匹配传入的schemaname和lookupcolumn参数,筛选出同一业务域下的所有值
  • 检查筛选出的值中是否包含待查询值,包含则返回存在,否则返回不存在

可直接复用的代码实现

using System;
using System.Collections.Generic;

public static class LookupCheck
{
    public static bool CheckValueExist(Dictionary<string, string> sourceDict, string schemaName, string lookupColumn, string targetValue)
    {
        if (sourceDict == null || sourceDict.Count == 0 
            || string.IsNullOrWhiteSpace(schemaName) 
            || string.IsNullOrWhiteSpace(lookupColumn)
            || string.IsNullOrWhiteSpace(targetValue))
        {
            return false;
        }

        foreach (var item in sourceDict)
        {
            // 拆分键,保留空项用于格式校验
            string[] keySegments = item.Key.Split(new[] { "::" }, StringSplitOptions.None);
            // 校验键必须为三段结构,且第一段lookupId不能为空
            if (keySegments.Length != 3 || string.IsNullOrWhiteSpace(keySegments[0]))
            {
                continue;
            }
            // 匹配schema和列名
            if (keySegments[1] == schemaName && keySegments[2] == lookupColumn)
            {
                // 值匹配直接返回结果
                if (item.Value == targetValue)
                {
                    return true;
                }
            }
        }
        return false;
    }
}

调用示例(对应测试场景)

// 初始化字典
Dictionary<string, string> KeyValueLookup1 = new Dictionary<string, string>();
KeyValueLookup1.Add("1::ldap::state","TX");
KeyValueLookup1.Add("2::ldap::state", "MN");
KeyValueLookup1.Add("3::ldap::state", "CF");
KeyValueLookup1.Add("4::ldap::language", "EN");
KeyValueLookup1.Add("5::ldap::language", "FR");

// 示例1:查询ldap、state下MN是否存在
bool result1 = LookupCheck.CheckValueExist(KeyValueLookup1, "ldap", "state", "MN"); 
// 返回true,符合预期

// 示例2:查询ldap、language下TA是否存在
bool result2 = LookupCheck.CheckValueExist(KeyValueLookup1, "ldap", "language", "TA"); 
// 返回false,符合预期

优化提示

  • 如果查询调用频率很高,可以在程序初始化阶段把字典按schemaname::lookupcolumn做分组缓存,避免每次查询遍历全量数据,性能提升明显
  • 如果业务需要不区分大小写匹配,可以在字符串比较时传入StringComparison.OrdinalIgnoreCase参数
  • 拆分键时不要使用StringSplitOptions.RemoveEmptyEntries,否则会把::ldap::state这类id为空的非法键误判为合规格式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 10:27:49