我有一个MultiValueDictionary<string, string>
,我试图按值获取密钥。
var dic = na.prevNext; // Getter to get MultiValueDictionary
string nodePointingToThisOne = "";
foreach (var item in dic)
{
if(item.Value == "test")
{
nodePointingToThisOne = item.Key;
}
break;
}
这不起作用,所以我尝试了Linq:
string nodePointingToThisOne = dic.Where(x => x.Value == this.nodeID).Select(x => x.Key);
但两者都出现了这个错误:Operator '==' cannot be applied to operands of type 'System.Collections.Generic.IReadOnlyCollection<string>' and 'string'
所以我的问题是如何让这个比较适用于只读集合?我知道如果一个密钥存在多次我会遇到问题,但我暂时将问题减少到了这个问题。
我看了 Get Dictionary key by using the dictionary value
LINQ: Getting Keys for a given list of Values from Dictionary and vice versa
Getting key of value of a generic Dictionary?
Get key from value - Dictionary<string, List<string>>
但他们处理的是“普通”字典。
答案 0 :(得分:0)
由于{self}的Value
属性可能包含多个值,因此无法使用==
运算符直接将其与某些字符串进行比较。请改用Contains()
:
.....
if (item.Value.Contains("test"))
{
.....
}
...或方法链版本:
string nodePointingToThisOne = dic.Where(x => x.Value.Contains("test"))
.Select(x => x.Key)
.FirstOrDefault();
答案 1 :(得分:0)
尝试按键进行迭代,然后比较值,并仅在值匹配时返回Key。
像这样:
foreach (var key in dic.Keys)
{
if(dic[key].Contains("your value"))
return key;
}
答案 2 :(得分:0)
您可以迭代这样的键
foreach (var key in dic.Keys)
{
if(key == "your key")
return key;
}
你也可以迭代这样的值
foreach (var v in dic.Values)
{
if(v == "your value")
return v;
}
示例:强>
Dictionary<string, string> c = new Dictionary<string, string>();
c.Add("Pk", "Pakistan");
c.Add("Aus", "Australia");
c.Add("Ind", "India");
c.Add("Nz", "New Zeland");
c.Add("SA", "South Africa");
foreach (var v in c.Values)
{
if (v == "Australia")
{
Console.WriteLine("Your Value is = " + v);
// perform your task
}
}
foreach (var k in c.Keys)
{
if (k == "Aus")
{
// perform your task
Console.WriteLine("Your Key is = " + k);
}
}
输出
你的价值是=&#34;澳大利亚&#34;
你的钥匙是=&#34; Aus&#34;
答案 3 :(得分:0)
如果你看一下MultiValueDictionary,第81行会给你一个提示。它是:
[TestInitialize]
public void TestInitialize()
{
MultiValueDictionary = new MultiValueDictionary<TestKey, string>();
}
protected static void AssertAreEqual( IDictionary<TestKey, string[]> expected,
IMultiValueDictionary<TestKey, string> actual )
{
Assert.AreEqual( expected.Count, actual.Count );
foreach ( var k in expected.Keys )
{
var expectedValues = expected[ k ];
var actualValues = actual[ k ];
AssertAreEqual( expectedValues, actualValues );
}
}
因此,对于您的情况,解决方案类似:
foreach (var item in dic.keys)
{
if(dict[item] == "test")
{
nodePointingToThisOne = item;
return nodePointingToThisOne;
}
}
答案 4 :(得分:-1)
为我工作:
foreach (int i in Dictionary.Keys)
{
if (Dictionary.Values.ToString() == "Your Value")
{
return Dictionary.Keys;
}
}