kUr4m4
kUr4m4

Reputation: 720

Index of List containing dictionaries of strings based on dictionary values

I have a List<Dictionary<string,string>> and I would like to get the index of the dictionary containing a specific value. I know this can be achieved with LINQ but I am totally lost as to how to get it...

Any help would be greatly appreciated!

Upvotes: 0

Views: 824

Answers (3)

Tim Schmelter
Tim Schmelter

Reputation: 460138

Presuming the List<Dictionary<string,string>> is 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);
}

If you just want the first match use matches.First().Index. This approach has the benefit that you also have the Dictionary and you have all matches if required.

Upvotes: 1

theonly112
theonly112

Reputation: 151

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

This returns -1 if the value is not contained in any of the dictionaries.

Upvotes: 3

Flat Eric
Flat Eric

Reputation: 8111

If you are sure the element is contained then you can use this:

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

If you are not sure, you have to test if it is contained:

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

Either you use ContainsKey or ContainsValue, dependent on, if the value you search for is a key or a value.

Upvotes: 2

Related Questions