将ContainsKey方法与变量一起使用

我有一个包含一些值的字符串变量,并且我希望能够检查该字符串是否以其变量名作为键存在于字典中。 为了更清楚地理解,您可以在以下代码中看到;

        string searchDuration = "200";

        var response = new Dictionary<string,string>()
        {
            {"searchDuration","200"},{"minRssi","-70"},{"optionalFilter","NO_FILTERS_actIVE_SCANNING"},{"txPowerLevel",{"peripheralId","123wrong"}
        };

我可以按照以下方式使用ContainsKey方法;

        if (response.ContainsKey("searchDuration"))
            if (searchDuration == pair.Value)
                isEqual = true;

但是我(实际上不能)以这种方式使用它,因为;

  • 我需要动态传递每个字符串变量,我不能将每个变量名称都写为字符串以传递给ConstainsKey方法
  • 它仅检查值,并且可能有多个带有“ 200”的值,这种情况给我错误的结果。
  • 我只想将值“ 200”与相关键“ searchDuration”进行比较,而不是与具有相同值的“ txPowerLevel”进行比较。

有没有一种方法可以检查字符串变量是否作为字典中的键存在,以将其值与字典成员进行比较?

iCMS 回答:将ContainsKey方法与变量一起使用

我建议这种方法:

string searchDuration = "200";

var response = new Dictionary<string,string>()
{
    {"searchDuration","200"},{"minRssi","-70"},{"optionalFilter","NO_FILTERS_ACTIVE_SCANNING"},{"txPowerLevel","-16"},{"peripheralId","123wrong"}
};

var wasItThere = response.TryGetValue(nameof(searchDuration),out var value);
Console.WriteLine(wasItThere && (value == searchDuration));

TryGetValueContainsKey更好,因为它在检查键是否存在的同时获取值。

nameof用于将变量名称转换为其字符串表示形式。

我明确使用过pair.Value,因为您原始问题中的代码强烈暗示您正在遍历Dictionary。这不是一个好主意(性能明智的选择)。

,

如果要比较的变量都是对象的一部分,则可以通过反射检查该对象,并将对象中找到的内容与字典中的内容进行比较。方法如下:

using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main()
    {
        var obj = new { searchDuration = "200",txPowerLevel = "100",other = "123"};

        var stringProperties = obj
            .GetType()
            .GetProperties()
            .Where(pi => pi.PropertyType == typeof(string) && pi.GetGetMethod() != null)
            .Select(pi => new
            {
                Name = pi.Name,Value = pi.GetGetMethod().Invoke(obj,null)}
            )
            .ToList();
        
        var response = new Dictionary<string,string>()
        {
            {"searchDuration","123wrong"}
        };

        foreach (var item in stringProperties)
        {
            string v;
            response.TryGetValue(item.Name,out v);         
            Console.WriteLine(item.Name + ": obj value=" + item.Value + ",response value=" + (v ?? "--N/A--"));
        }
    }
}

工作小提琴:https://dotnetfiddle.net/gUNbRq

如果项目以局部变量的形式存在,那么也可以将其完成(例如,参见here),但是我建议将其放在对象中,以保持要检查的值与其他变量分开方法的需求和用途。

本文链接:https://www.f2er.com/2076321.html

大家都在问