How to

get key from dictionary by value

Published: 27. October 2011 | Updated: 27. October 2011
License: Microsoft Public License (MS-PL)
Categories: Collections
Tags: C# Collections Linq
Was this snippet helpful for you? YESYES / NONO

Import namespaces

using System.Collections.Generic;
using System.Linq;

Code

var dictionary = new Dictionary<int, string>();

dictionary.Add(1, "a");
dictionary.Add(3, "c");
dictionary.Add(6, "c");
dictionary.Add(7, "e");

int[] keysByValue = dictionary.Where(x => x.Value == "c").Select(pair => pair.Key).ToArray();

foreach (var i in keysByValue)
{
    Console.WriteLine(i);
}
Console Output:
3
6
Send us feedback about this snippet »



Related Snippets: