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

如何将ContainsKey三元表达式转换为TryGetValue?技术咨询

Convert Dictionary Ternary Checks to TryGetValue Syntax

Hey there! Converting those ternary ContainsKey checks to TryGetValue is a smart upgrade—it cuts down on redundant dictionary lookups (way more efficient, especially with 25 instances like you have) and makes your logic cleaner overall. Let's break this down step by step.

Single Instance Conversion

First, let's take your original line:

filters.ContainsKey("companyCode") ? filters["companyCode"] : string.Empty;

Option 1: Explicit Block Logic (Most Readable)

This approach is great if you need to handle additional logic when building your query, and it avoids the double lookup of your original code:

string companyCode = string.Empty;
if (filters.TryGetValue("companyCode", out companyCode))
{
    // Key exists—companyCode holds the value here for your query
}
// If the key doesn't exist, companyCode stays as string.Empty automatically

Option 2: Inline Ternary (Concise One-Liner)

If you want to keep it tight like your original code, you can wrap TryGetValue in a ternary:

string companyCode = filters.TryGetValue("companyCode", out string value) ? value : string.Empty;

Cut Repetition for 25 Instances

Since you've got ~25 of these checks, creating a reusable extension method will eliminate duplicate code and make your query-building logic way easier to maintain.

Add this static extension method to your project:

public static class DictionaryExtensions
{
    // Adjust the dictionary type if your filters aren't <string, string>
    public static string GetValueOrDefault(this Dictionary<string, string> dictionary, string key)
    {
        return dictionary.TryGetValue(key, out string value) ? value : string.Empty;
    }
}

Now you can replace every single ternary check with this clean one-liner:

string companyCode = filters.GetValueOrDefault("companyCode");
string department = filters.GetValueOrDefault("department");
// Repeat this pattern for all 25 keys in your query...

Why This Upgrade Pays Off

  • Performance: Your original code does two separate dictionary lookups (ContainsKey + indexer access). TryGetValue does it in one pass, which adds up with 25 checks.
  • Maintainability: The extension method centralizes your "default to empty string" rule—if you ever need to change the default value later, you only update it once.
  • Readability: The method name GetValueOrDefault makes your code's intent crystal clear at a glance.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:04:22