繁体   English   中英

使用带有变量的 ContainsKey 方法

[英]Usage of ContainsKey method with a variable

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

        string searchDuration = "200";

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

我可以使用 ContainsKey 方法,如下所示;

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

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

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

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

我建议这种方法:

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 这不是一个好主意(性能方面)。

如果您要比较的变量都是 object 的一部分,那么您可以通过反射检查 object,并将 object 中的内容与字典中的内容进行比较。 方法如下:

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","200"},
            {"minRssi", "-70"},
            {"optionalFilter","NO_FILTERS_ACTIVE_SCANNING"},
            {"txPowerLevel","200"},
            {"peripheralId","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

如果这些项目作为局部变量存在,那么它也可以完成(例如,请参见此处),但我建议将其放在 object 中,以使您要检查的值与您的方法需要和使用的其他变量分开。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM