Brini Brini - 2 months ago 12
C# Question

Get dictionary key if value contains string

I have this Dictionary:

static Dictionary<int, string> Players = new Dictionary<int, string>();
dictionary.Add(1, "Chris [GC]");
dictionary.Add(2, "John");
dictionary.Add(3, "Paul");
dictionary.Add(4, "Daniel [GC]");


I want to get the key of values that contains "[GC]"

Any idea how?

Thanks.

Answer

Use a query like below.

   var itemsWithGC = dictionary.Where(d => d.Value.Contains("[GC]")).Select(d => d.Key).ToList();
   foreach (var i in itemsWithGC)
   {
       Console.WriteLine(i);
   }
Comments