我有一个 Dictionary<string, string>[]
数组,其中每个元素都是一个 Dictionary<string, string>
,具有相同的键和不同的值。
如何为给定的 Key 和 Value 获取对象的索引?
例如,如果字典数组有两个元素为:
[0]: {'Key1', 'ValueA}
{'Key2', 'ValueB}
[1]: {'Key1', 'ValueC}
{'Key2', 'ValueD}
如何获取'Key2' = 'ValueD'的索引?因此,索引结果 = 1。
答案 0 :(得分:2)
您可以使用以下 LINQ 查询,它就像一个尽快中断的循环:
int index = dictionaries
.Select((dict, index) => (dict, index)) // put the dictionary and it's index in a ValueTuple
.Where(x => x.dict.Any(kv => kv.Key == "Key2" && kv.Value == "ValueD")) // filter by key & value
.Select(x => x.index) // select the index
.DefaultIfEmpty(-1) // if no dictionary met the condition you want -1 as result
.First(); // this is safe, you get either a single index or -1 as fallback
但请注意,您的方法正在失去字典的快速查找功能。
编辑:Somebody's approach 效率更高,您可以将其与此结合使用:
int index = dictionaries
.Select((dict, index) => (dict, index)) // put the dictionary and it's index in a ValueTuple
.Where(x => x.dict.TryGetValue("Key2", out string value) && value == "ValueD") // filter by key & value
.Select(x => x.index) // select the index
.DefaultIfEmpty(-1) // if no dictionary met the condition you want -1 as result
.First(); // this is safe, you get either a single index or -1 as fallback
答案 1 :(得分:2)
在这个解决方案中,在每个字典中搜索给定值是 O(1) 而不是其他解决方案中的 O(n):
string expectedKey = "Key2";
string expectedValue = "ValueD";
var item = array.FirstOrDefault(x => x.TryGetValue(expectedKey , out string value) && value == expectedValue);
if(item == null)
{
Console.WriteLine("entry wasn't found in any dictionary");
return;
}
int index = Array.IndexOf(array, item);
答案 2 :(得分:1)
var item = array.Where(x=>x.Any(y=>y.Key == "Key2" && y.Value == "ValueD")).First();
var index = array.IndexOf(item);