xxxxxxxxxx
Dictionary<string, string> myDictionary = new Dictionary<string, string>();
myDictionary.Add("key1", "value1");
myDictionary.Add("key2", "value2");
string key = "key2";
if (myDictionary.ContainsKey(key))
{
string value = myDictionary[key];
Console.WriteLine("Value for key '{0}': {1}", key, value);
}
else
{
Console.WriteLine("Key '{0}' does not exist in the dictionary.", key);
}
xxxxxxxxxx
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("UserID", "test");
string userIDFromDictionaryByKey = dict["UserID"];
xxxxxxxxxx
public static string GetKeyFromValue(string valueVar)
{
foreach (string keyVar in dictionaryVar.Keys)
{
if (dictionaryVar[keyVar] == valueVar)
{
return keyVar;
}
}
return null;
}
xxxxxxxxxx
// Declare and initialize a dictionary
Dictionary<string, int> myDictionary = new Dictionary<string, int>();
// Add some key-value pairs to the dictionary
myDictionary.Add("apple", 5);
myDictionary.Add("banana", 10);
myDictionary.Add("orange", 8);
// Retrieve a value from the dictionary using a specific key
string key = "banana";
if (myDictionary.ContainsKey(key))
{
int value = myDictionary[key];
Console.WriteLine("Value for key '{0}': {1}", key, value);
}
else
{
Console.WriteLine("Key '{0}' does not exist in the dictionary.", key);
}
xxxxxxxxxx
public static List<TKey> GetKeysByValue<TKey, TValue>(Dictionary<TKey, TValue> dictionary, TValue value)
{
List<TKey> keys = new List<TKey>();
foreach (var pair in dictionary)
{
if (pair.Value.Equals(value))
{
keys.Add(pair.Key);
}
}
return keys;
}
// Example usage:
Dictionary<int, string> dictionary = new Dictionary<int, string>
{
{ 1, "apple" },
{ 2, "banana" },
{ 3, "orange" }
};
string searchValue = "banana";
List<int> keys = GetKeysByValue(dictionary, searchValue);
// Print the keys
foreach (var key in keys)
{
Console.WriteLine(key);
}
xxxxxxxxxx
Dictionary<string, string> dict = new Dictionary<string, string>()
{
{"1", "one"},
{"2", "two"},
{"3", "three"}
};
foreach (var item in dict)
{
if(item.Value == "One")
{
var firstElementKey = item.Key;
Console.WriteLine(firstElementKey);
}
}