2014-12-05 90 views

回答

3
int index = listOfDictionaries.FindIndex(dict => dict.ContainsValue("some value")); 

如果該值未包含在任何字典中,則返回-1。

+0

謝謝!太棒了! – kUr4m4 2014-12-05 14:20:35

2

如果您不確定元素包含那麼你可以使用這個:

int idx = list.IndexOf(list.Single(x => x.ContainsValue("value"))); 

如果你不知道,你要測試是否包含:

var match = list.SingleOrDefault(x => x.ContainsValue("value")); 
int idx = match != null ? list.IndexOf(match) : -1; 

無論您使用ContainsKeyContainsValue,取決於,如果您搜索的值是一個鍵或值。

+0

謝謝! +1的幫助和正確的答案,但我將選擇僅作爲正確的答案,因爲它不需要額外的檢查返回-1,並且如果鍵/值不存在則不會拋出錯誤! – kUr4m4 2014-12-05 14:20:18

1

。假定該List<Dictionary<string,string>>dictionaries

var matches = dictionaries 
    .Select((d, ix) => new { Dictionary = d, Index = ix }) 
    .Where(x => x.Dictionary.Values.Contains("specificValue")); // or ContainsValue as the Eric has shown 

foreach(var match in matches) 
{ 
    Console.WriteLine("Index: " + match.Index); 
} 

如果你只是想在第一場比賽使用matches.First().Index。這種方法的好處是你也有Dictionary,如果需要,你有所有匹配。

+0

謝謝,雖然它比我需要的方式:) +1幫助 – kUr4m4 2014-12-05 14:18:17