2014-12-05 85 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