检查数字是否包含在Dictionary数组C#中

时间:2017-11-21 09:30:24

标签: c# arrays dictionary

我有Dictionary,键是一个int数组,值是一个字符串。如何通过检查密钥数组中是否包含int来获取值?

public static Dictionary<int[], string> MyDic = new Dictionary<int[], string>
{
    {new int[]{2,25},"firstValue"},
    {new int[]{3,91,315,322},"secondValue"}
};

我有:

int number=91;
string value=?;

我需要值"secondValue"

4 个答案:

答案 0 :(得分:6)

我认为这是一个糟糕的设计选择。如果密钥之间的数字不重复(正如您在问题评论中所述),那么只需将密钥压缩为简单的Dictionary<int,string>即可。只是让不同的整数都是相同字符串的键。

例如:

Dictionary<int,string>
{
    [2] = "firstValue",
    [25] = "firstValue",
};

为了不重复相同的值而是重复不同的对象,您可以在那里放置引用:

string firstValue = "firstValue";
Dictionary<int,string>
{
    [2] = firstValue,
    [25] = firstValue,
};

在这种情况下,为一个键更改值的内容(不是对于字符串,因为它是不可变的,但如果它是某个其他对象)将为所有更改。

答案 1 :(得分:1)

使用contains和foreach循环(比其他解决方案更易读):

string value;
int number = 91;

foreach(KeyValuePair<int[], string> entry in MyDic)
{
    if (entry.Key.Contains(number))
    {
        value = entry.Value;
    }
}

然而,字典可能不是正确的选择。 查看Gilads的答案,了解您可以使用的其他结构

答案 2 :(得分:1)

string value = MyDic.FirstOrDefault(x => x.Key.Contains(number)).Value;

?不需要,不能申请? KeyValuePair的操作数

答案 3 :(得分:-1)

类似

value = MyDic.FirstOrDefault(x => x.Key.Contains(number)).Value;

将返回第一个匹配项或null