在地图上搜索键和值

本文关键字:键和值 搜索 地图 | 更新日期: 2023-09-27 18:34:51

我正在寻找一个允许我搜索键和值的数据库结构。现在我正在使用一个简单的字典,但是如果我在其中搜索值,我必须循环所有键(如果我是对的,则具有O(n(。但是由于我的地图很小(只有 5 个条目(,我不确定这是否重要。

Dictionary<string, int> myDict = new Dictionary<string, int> {
    {"first", 1},
    {"second", 2},
    {"third", 3},
    {"fourth", 4},
    {"fifth", 5}
}

现在,通过按键访问地图很容易:

var myInt = myDict["second"]; // O(1)

但是因为我需要经常访问这个地图(对于键和值(,我不确定是否有更好的方法来存储值,然后:

var myString = myDict.Single(x => x.Value == 2).Key; // O(n)

在地图上搜索键和值

从讨论中,我们了解到您的值也是唯一的,因此您可以保留两个地图:

Dictionary<string, int> myDict = new Dictionary<string, int> {
    {"first", 1},
    {"second", 2},
    {"third", 3},
    {"fourth", 4},
    {"fifth", 5}
}
Dictionary<int, string> myReverseDict = new Dictionary<int, string {
    {1, "first"},
    {2, "second"},
    {3, "third"},
    {4, "fourth"},
    {5, "fifth"}
}

如果字典数据在运行时发生更改,则应编写一个方法来同步两个字典。

这种方法简单、快速且用途广泛,但是当数据更改时会产生开销。

考虑一个枚举(如果你的列表总是相同的(:

enum MyDic
{
  First = 1,
  Second,
  Third,
  Fourth,
  Fifth
}
这使得"按键获取值">

和"按键获取值"都变得容易:

var stringResult = (MyDic) 1; // returns First, use ToString() to get "First" as text.
var numResult = (int) MyDic.First; // returns 1

看看这个:

class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(((MyDic)1).ToString());
            Console.WriteLine((int)MyDic.First);
            Console.ReadKey();
        }
    }    

注意:使用属性Description用不同的文本描述您的值,可能会使enum过于复杂:

 enum MyDic
 {
      [Description("Uno")]
      First = 1,
      Second,
      Third,
      Fourth,
      Fifth
 }

但是检索值的方法比简单的方法要长得多(记住KISS原则(