如何将ContainsKey三元表达式转换为TryGetValue?技术咨询
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).TryGetValuedoes 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
GetValueOrDefaultmakes your code's intent crystal clear at a glance.
内容的提问来源于stack exchange,提问作者jeffkenn

