How do I get a Dictionary key by value in C#?
Dictionary<string, string> types = new Dictionary<string, string>()
{
{"1", "one"},
{"2", "two"},
{"3", "three"}
};
I want something like this:
getByValueKey(string value);
getByValueKey("one") must be return "1".
What is the best way do this? Maybe HashTable or SortedLists?
Values do not necessarily have to be unique, so you have to do a lookup. You can do something like this:
var myKey = types.FirstOrDefault(x => x.Value == "one").Key;
If values are unique and are inserted less frequently than read, then create an inverse dictionary where values are keys and keys are values.
You could do that:
By looping through all the KeyValuePair<TKey, TValue>'s in the dictionary (which will be a sizable performance hit if you have a number of entries in the dictionary)
Use two dictionaries, one for value-to-key mapping and one for key-to-value mapping (which would take up twice as much space in memory).
Use Method 1 if performance is not a consideration, and use Method 2 if memory is not a consideration.
Also, all keys must be unique, but the values are not required to be unique. You may have more than one key with the specified value.
I was in a situation where LINQ binding was not available and had to expand lambda explicitly. It resulted in a simple function:
public static T KeyByValue<T, W>(this Dictionary<T, W> dict, W val)
{
T key = default;
foreach (KeyValuePair<T, W> pair in dict)
{
if (EqualityComparer<W>.Default.Equals(pair.Value, val))
{
key = pair.Key;
break;
}
}
return key;
}
Call it like follows:
public static void Main()
{
Dictionary<string, string> dict = new Dictionary<string, string>()
{
{"1", "one"},
{"2", "two"},
{"3", "three"}
};
string key = dict.KeyByValue("two");
Console.WriteLine("Key: " + key);
}
It works on .NET 2.0 and in other limited environments.
public static string GetKeyFromValue(string valueVar)
{
foreach (string keyVar in dictionaryVar.Keys)
{
if (dictionaryVar[keyVar] == valueVar)
{
return keyVar;
}
}
return null;
}
Other people may have more efficient answers, but I find this personally more intuitive and it works in my case.
I have created a double-lookup class:
/// <summary>
/// dictionary with double key lookup
/// </summary>
/// <typeparam name="T1">primary key</typeparam>
/// <typeparam name="T2">secondary key</typeparam>
/// <typeparam name="TValue">value type</typeparam>
public class cDoubleKeyDictionary<T1, T2, TValue> {
private struct Key2ValuePair {
internal T2 key2;
internal TValue value;
}
private Dictionary<T1, Key2ValuePair> d1 = new Dictionary<T1, Key2ValuePair>();
private Dictionary<T2, T1> d2 = new Dictionary<T2, T1>();
/// <summary>
/// add item
/// not exacly like add, mote like Dictionary[] = overwriting existing values
/// </summary>
/// <param name="key1"></param>
/// <param name="key2"></param>
public void Add(T1 key1, T2 key2, TValue value) {
lock (d1) {
d1[key1] = new Key2ValuePair {
key2 = key2,
value = value,
};
d2[key2] = key1;
}
}
/// <summary>
/// get key2 by key1
/// </summary>
/// <param name="key1"></param>
/// <param name="key2"></param>
/// <returns></returns>
public bool TryGetValue(T1 key1, out TValue value) {
if (d1.TryGetValue(key1, out Key2ValuePair kvp)) {
value = kvp.value;
return true;
} else {
value = default;
return false;
}
}
/// <summary>
/// get key1 by key2
/// </summary>
/// <param name="key2"></param>
/// <param name="key1"></param>
/// <remarks>
/// 2x O(1) operation
/// </remarks>
/// <returns></returns>
public bool TryGetValue2(T2 key2, out TValue value) {
if (d2.TryGetValue(key2, out T1 key1)) {
return TryGetValue(key1, out value);
} else {
value = default;
return false;
}
}
/// <summary>
/// get key1 by key2
/// </summary>
/// <param name="key2"></param>
/// <param name="key1"></param>
/// <remarks>
/// 2x O(1) operation
/// </remarks>
/// <returns></returns>
public bool TryGetKey1(T2 key2, out T1 key1) {
return d2.TryGetValue(key2, out key1);
}
/// <summary>
/// get key1 by key2
/// </summary>
/// <param name="key2"></param>
/// <param name="key1"></param>
/// <remarks>
/// 2x O(1) operation
/// </remarks>
/// <returns></returns>
public bool TryGetKey2(T1 key1, out T2 key2) {
if (d1.TryGetValue(key1, out Key2ValuePair kvp1)) {
key2 = kvp1.key2;
return true;
} else {
key2 = default;
return false;
}
}
/// <summary>
/// remove item by key 1
/// </summary>
/// <param name="key1"></param>
public void Remove(T1 key1) {
lock (d1) {
if (d1.TryGetValue(key1, out Key2ValuePair kvp)) {
d1.Remove(key1);
d2.Remove(kvp.key2);
}
}
}
/// <summary>
/// remove item by key 2
/// </summary>
/// <param name="key2"></param>
public void Remove2(T2 key2) {
lock (d1) {
if (d2.TryGetValue(key2, out T1 key1)) {
d1.Remove(key1);
d2.Remove(key2);
}
}
}
/// <summary>
/// clear all items
/// </summary>
public void Clear() {
lock (d1) {
d1.Clear();
d2.Clear();
}
}
/// <summary>
/// enumerator on key1, so we can replace Dictionary by cDoubleKeyDictionary
/// </summary>
/// <param name="key1"></param>
/// <returns></returns>
public TValue this[T1 key1] {
get => d1[key1].value;
}
/// <summary>
/// enumerator on key1, so we can replace Dictionary by cDoubleKeyDictionary
/// </summary>
/// <param name="key1"></param>
/// <returns></returns>
public TValue this[T1 key1, T2 key2] {
set {
lock (d1) {
d1[key1] = new Key2ValuePair {
key2 = key2,
value = value,
};
d2[key2] = key1;
}
}
}
A Dictionary<K,V> extension that works. I have been using it for a long time::
public static bool TryGetKey<K, V>(this IDictionary<K, V> instance, V value, out K key)
{
foreach (var entry in instance)
{
if (!entry.Value.Equals(value))
{
continue;
}
key = entry.Key;
return true;
}
key = default(K);
return false;
}
And use as :
public static void Main()
{
Dictionary<string, string> dict = new Dictionary<string, string>()
{
{"1", "one"},
{"2", "two"},
{"3", "three"}
};
string value="two";
if (dict.TryGetKey(value, out var returnedKey))
Console.WriteLine($"Found Key {returnedKey}");
else
Console.WriteLine($"No key found for value {value}");
}
Maybe something like this:
foreach (var keyvaluepair in dict)
{
if(Object.ReferenceEquals(keyvaluepair.Value, searchedObject))
{
//dict.Remove(keyvaluepair.Key);
break;
}
}
The order of the keys in Keys is unspecified, but it is the same as the associated values in Values (from the C# doc).
So an efficient way (in some situations) to do that for a collection of values looks like:
/// <summary>
/// Gets the 1st key matching each value
/// </summary>
public static IEnumerable<TKey> GetKeys<TKey,TValue>(this Dictionary<TKey, TValue> dic, IEnumerable<TValue> values) where TKey : notnull
{
//The order of the keys in Keys is unspecified, but it is the same as the associated values in Values
var dicKeys = dic.Keys.ToList();
var dicValues = dic.Values.ToList();
foreach (var value in values)
{
var i = dicValues.IndexOf(value); //Will return the index of the 1st found value, even when multiple values are present
//we could test if i==-1 there.
yield return dicKeys[i];
}
}
types.Values.ToList().IndexOf("one");
Values.ToList() converts your dictionary values into a List of objects.
IndexOf("one") searches your new List looking for "one" and returns the Index which would match the index of the Key/Value pair in the dictionary.
This method does not care about the dictionary keys, it simply returns the index of the value that you are looking for.
Keep in mind there may be more than one "one" value in your dictionary. And that is the reason there is no "get key" method.
The below code only works if it contains unique value data:
public string getKey(string Value)
{
if (dictionary.ContainsValue(Value))
{
var ListValueData = new List<string>();
var ListKeyData = new List<string>();
var Values = dictionary.Values;
var Keys = dictionary.Keys;
foreach (var item in Values)
{
ListValueData.Add(item);
}
var ValueIndex = ListValueData.IndexOf(Value);
foreach (var item in Keys)
{
ListKeyData.Add(item);
}
return ListKeyData[ValueIndex];
}
return string.Empty;
}
I have a very simple way to do this. It worked out perfect for me.
Dictionary<string, string> types = new Dictionary<string, string>();
types.Add("1", "one");
types.Add("2", "two");
types.Add("3", "three");
Console.WriteLine("Please type a key to show its value: ");
string rLine = Console.ReadLine();
if(types.ContainsKey(rLine))
{
string value_For_Key = types[rLine];
Console.WriteLine("Value for " + rLine + " is" + value_For_Key);
}
Related
TL;DR: I was trying to create a class which would hold nested JSON data.
I eventually solved my own problem, but #dbc was very helpful and they have a solution which may be slightly faster if you want to implement it their way. I have fully documented my solution, with example usage, and marked it as answered below.
I'm creating a project in which I intend to store lots of nested JSON data.
Instead of creating a hundred classes, each with their own variables/attributes, and then having to modify them every time I want to change something, I'd like to create a simple "dynamic object".
This object holds the root of all data, as well as all the children's data. In JSON, this is represented by:
{
"name":"foo",
"id":0,
"attributes":
{
"slippery":true,
"dangerous":true
},
"costs":
{
"move":1,
"place":2,
"destroy":3
}
}
where the root structure holds the data "name" and "id", as well as children "attributes" and "costs" each containing their own data.
I'm using the json.net library for this, and my current class looks like this:
public class Data : JObject
{
public void CreateChildUnderParent(string parent, string child)
{
Data obj = GetValueOfKey<Data>(parent);
if(obj != null)
obj.CreateChild(child);
}
public void CreateChild(string child)
{
AddKey(child, new Data());
}
public void AddKeyToParent(string parent, string key, JToken value)
{
Data parentObject = GetValueOfKey<Data>(parent);
if(parentObject != null)
parentObject.AddKey(key, value);
}
public void AddKey(string key, JToken value)
{
Add(key, value);
}
public void RemoveKeyFromParent(string parent, string key)
{
Data parentObject = GetValueOfKey<Data>(parent);
if(parentObject != null)
parentObject.RemoveKey(key);
}
public void RemoveKey(string key)
{
Remove(key);
}
public T GetValueFromParent<T>(string parent, string key)
{
Data parentObject = GetValueOfKey<Data>(parent);
if(parentObject != null)
return parentObject.GetValue(key).ToObject<T>();
return default;
}
public T GetValueOfKey<T>(string key)
{
foreach (var kvp in this)
if (kvp.Value is Data)
{
T value = ((Data)kvp.Value).GetValueOfKey<T>(key);
if (value != null)
return value;
}
JToken token = GetValue(key);
if(token != null)
return token.ToObject<T>(); //throws exception
return default;
}
}
I can add children just fine, but my issue comes when I try to access them. An InvalidCastException is thrown within my
public T GetValueOfKey<T>(string key)
method whenever I call it using
Data
as the generic type.
For example:
Data data = GetValueOfKey<Data>("attributes");
throws an exception. I'm not sure why this is happening, so any help would be greatly appreciated!
EDIT:
Here is the complete error log thrown:
InvalidCastException: Specified cast is not valid.
(wrapper castclass) System.Object.__castclass_with_cache(object,intptr,intptr)
Newtonsoft.Json.Linq.JToken.ToObject[T] () (at <97722d3abc9f4cf69f9e21e6770081b3>:0)
Data.GetValueOfKey[T] (System.String key) (at Assets/Scripts/Attributes/Object/Data.cs:74)
Data.AddKeyToParent (System.String parent, System.String key, Newtonsoft.Json.Linq.JToken value) (at Assets/Scripts/Attributes/Object/Data.cs:23)
DataController.Awake () (at Assets/Scripts/Controllers/DataController.cs:35)
and an example of instantiation which causes this exception:
public class DataController
{
void Awake()
{
Data data = new Data();
data.AddKey("name", "foo");
data.CreateChild("attributes");
data.AddKeyToParent("attributes", "slippery", true); //throws exception (line 35)
}
}
UPDATE (10/20/18):
Ok so I went through my code this afternoon and rewrote it as a wrapper class, now the root JObject is stored within a variable in my Data, and accessor methods adjust its properties.
However, I ran into a problem. Here's the updated class (minified to the problem):
public class Data
{
public JObject data;
public Data()
{
data = new JObject();
}
public void AddChild(string child)
{
data.Add(child, new JObject());
}
public void AddKeyWithValueToParent(string parent, string key, JToken value)
{
JObject parentObject = GetValueOfKey<JObject>(parent);
if(parentObject != null)
parentObject.Add(key, value);
}
public void AddKeyWithValue(string key, JToken value)
{
data.Add(key, value);
}
public T GetValueOfKey<T>(string key)
{
return GetValueOfKey<T>(key, data);
}
private T GetValueOfKey<T>(string key, JObject index)
{
foreach (var kvp in index)
if (kvp.Value is JObject)
{
T value = GetValueOfKey<T>(key, kvp.Value.ToObject<JObject>());
if (value != null)
return value;
}
JToken token = index.GetValue(key);
if (token != null)
return token.ToObject<T>();
return default;
}
}
And here is an example of how to construct a Data object, and use its methods:
public class DataController
{
void Awake() {
Data data = new Data();
data.AddKeyWithValue("name", "foo");
data.AddChild("attributes");
data.AddKeyWithValueToParent("attributes", "slippery", true);
}
}
So everything in terms of adding key-value pairs, and creating children works wonderfully! No InvalidCastException at all, yay! However, when I try to serialize the object through JsonConvert.SerializeObject(data), it doesn't fully serialize it.
I have the program output to the console to show the serialization, and it looks like this:
{"data":{"name":"foo","attributes":{}}}
I've already checked to make sure that when I call data.AddKeyWithValueToParent("attributes", "slippery", true), it does indeed find the JObject value with the key attributes and even appears to successfully add the new key-value pair "slippery":true under it. But for some reason, serializing the root object data does not seem to identify that anything lies within the attributes object. Thoughts?
What I think may be happening, is that the value returned from GetValueOfKey is not acting as a reference object, but rather an entirely new object, so changes to that are not reflected within the original object.
I figured it out! I was right, the value returned from my GetValueOfKey method was returning a completely new object, and not a reference to the instance it found. Looking through my code, that should have been immediately obvious, but I'm tired and I was hoping for everything to be easy haha.
Anyway, for anyone who ever has the same question, and is just looking for a simple way to store and read some nested key-value pairs using the Json.NET library, here is the finished class that will do that (also serializable, and deserializable using JsonConvert):
public class Data
{
[JsonProperty]
private JObject data;
public Data()
{
data = new JObject();
}
public void AddChildUnderParent(string parent, string child)
{
JObject parentObject = GetValueOfKey<JObject>(parent);
if (parentObject != null)
{
parentObject.Add(child, new JObject());
ReplaceObject(parent, parentObject);
}
}
public void AddChild(string child)
{
data.Add(child, new JObject());
}
public void AddKeyWithValueToParent(string parent, string key, JToken value)
{
JObject parentObject = GetValueOfKey<JObject>(parent);
if(parentObject != null)
{
parentObject.Add(key, value);
ReplaceObject(parent, parentObject);
}
}
public void AddKeyWithValue(string key, JToken value)
{
data.Add(key, value);
}
public void RemoveKeyFromParent(string parent, string key)
{
JObject parentObject = GetValueOfKey<JObject>(parent);
if (parentObject != null)
{
parentObject.Remove(key);
ReplaceObject(parent, parentObject);
}
}
public void RemoveKey(string key)
{
data.Remove(key);
}
public T GetValueFromParent<T>(string parent, string key)
{
JObject parentObject = GetValueOfKey<JObject>(parent);
if (parentObject != null)
return parentObject.GetValue(key).ToObject<T>();
return default;
}
public T GetValueOfKey<T>(string key)
{
return GetValueOfKey<T>(key, data);
}
private T GetValueOfKey<T>(string key, JObject index)
{
foreach (var kvp in index)
if (kvp.Value is JObject)
{
T value = GetValueOfKey<T>(key, (JObject)kvp.Value);
if (value != null)
return value;
}
JToken token = index.GetValue(key);
if (token != null)
{
data = token.Root.ToObject<JObject>();
return token.ToObject<T>();
}
return default;
}
public void ReplaceObject(string key, JObject replacement)
{
ReplaceObject(key, data, replacement);
}
private void ReplaceObject(string key, JObject index, JObject replacement)
{
foreach (var kvp in index)
if (kvp.Value is JObject)
ReplaceObject(key, (JObject)kvp.Value, replacement);
JToken token = index.GetValue(key);
if (token != null)
{
JToken root = token.Root;
token.Replace(replacement);
data = (JObject)root;
}
}
}
That should get anyone a good head start. I plan on updating my code with params modifiers in some places to allow for multiple calls, but for now I'm just happy that I got it working. You'll notice that I had to create a ReplaceObject method, because without it, the original private JObject data was never actually updated to account for the changes made to the variable returned from GetValueOfKey.
Anyway, a big thanks to #dbc for all their help during this whole thing, and I hope this post helps someone in the future!
-ShermanZero
EDIT:
So I spent a little more time developing the class, and I think I have it pinned down to a universal point where anyone could simply copy-paste and easily implement it into their own program. Although, I personally think that #dbc has a faster solution if you care about nanosecond-millisecond differences in speed. For my own personal use though, I don't think it will make much of a difference.
Here is my full implementation, complete with documentation and error logging:
public class Data
{
[JsonExtensionData]
private JObject root;
private Texture2D texture;
private char delimiter = ',';
/// <summary>
/// Creates a new Data class with the default delimiter.
/// </summary>
public Data()
{
root = new JObject();
}
/// <summary>
/// Creates a new Data class with a specified delimiter.
/// </summary>
/// <param name="delimiter"></param>
public Data(char delimiter) : this()
{
this.delimiter = delimiter;
}
/// <summary>
/// Adds a child node to the specified parent(s) structure, which is split by the delimiter, with the specified name.
/// </summary>
/// <param name="name"></param>
/// <param name="parents"></param>
public void AddChild(string name, string parents)
{
AddChild(name, parents.Split(delimiter));
}
/// <summary>
/// Adds a child node to the specified parent(s) structure with the specified name.
/// </summary>
/// <param name="name"></param>
/// <param name="parents"></param>
public void AddChild(string name, params string[] parents)
{
string lastParent;
JObject parentObject = ReturnParentObject(out lastParent, parents);
if (parentObject != null)
{
parentObject.Add(name, new JObject());
ReplaceObject(lastParent, parentObject, parents);
} else
{
string message = "";
foreach (string parent in parents)
message += parent + " -> ";
throw new ParentNotFoundException($"The parent '{ message.Substring(0, message.LastIndexOf("->")) }' was not found.");
}
}
/// <summary>
/// Adds a child node to the root structure with the specified name.
/// </summary>
/// <param name="name"></param>
public void AddChild(string name)
{
root.Add(name, new JObject());
}
/// <summary>
/// Adds the specified key-value pair to the specified parent(s) structure, which is split by the delimiter.
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="parents"></param>
public void AddKeyWithValue(string key, JToken value, string parents)
{
AddKeyWithValue(key, value, parents.Split(delimiter));
}
/// <summary>
/// Adds the specified key-value pair to the specified parent(s) structure.
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="parents"></param>
public void AddKeyWithValue(string key, JToken value, params string[] parents)
{
string lastParent;
JObject parentObject = ReturnParentObject(out lastParent, parents);
if (parentObject != null)
{
parentObject.Add(key, value);
ReplaceObject(lastParent, parentObject, parents);
} else
{
string message = "";
foreach (string parent in parents)
message += parent + " -> ";
throw new ParentNotFoundException($"The parent '{ message.Substring(0, message.LastIndexOf("->")) }' was not found.");
}
}
/// <summary>
/// Adds the specified key-value pair to the root structure.
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
public void AddKeyWithValue(string key, JToken value)
{
root.Add(key, value);
}
/// <summary>
/// Removes the specified key from the specified parent(s) structure, which is split by the delimiter.
/// </summary>
/// <param name="key"></param>
/// <param name="parents"></param>
public void RemoveKey(string key, string parents)
{
RemoveKey(key, parents.Split(delimiter));
}
/// <summary>
/// Removes the specified key from the specified parent(s) structure.
/// </summary>
/// <param name="key"></param>
/// <param name="parents"></param>
public void RemoveKey(string key, params string[] parents)
{
string lastParent;
JObject parentObject = ReturnParentObject(out lastParent, parents);
if (parentObject != null)
{
parentObject.Remove(key);
ReplaceObject(lastParent, parentObject, parents);
} else
{
string message = "";
foreach (string parent in parents)
message += parent + " -> ";
throw new ParentNotFoundException($"The parent '{ message.Substring(0, message.LastIndexOf("->")) }' was not found.");
}
}
/// <summary>
/// Removes the specified key from the root structure.
/// </summary>
/// <param name="key"></param>
public void RemoveKey(string key)
{
root.Remove(key);
}
/// <summary>
/// Returns if the specified key is contained within the parent(s) structure, which is split by the delimiter.
/// </summary>
/// <param name="key"></param>
/// <param name="parents"></param>
/// <returns></returns>
public bool HasValue(string key, string parents)
{
return HasValue(key, parents.Split(delimiter));
}
/// <summary>
/// Returns if the specified key is contained within the parent(s) structure.
/// </summary>
/// <param name="key"></param>
/// <param name="parents"></param>
/// <returns></returns>
public bool HasValue(string key, params string[] parents)
{
//string lastParent = parents[parents.Length - 1];
//Array.Resize(ref parents, parents.Length - 1);
string lastParent;
JObject parentObject = ReturnParentObject(out lastParent, parents);
if (parentObject == null)
return false;
else if (parentObject == root && parents.Length > 0)
return false;
IDictionary<string, JToken> dictionary = parentObject;
return dictionary.ContainsKey(key);
}
/// <summary>
/// Returns the deepest parent object referenced by the parent(s).
/// </summary>
/// <param name="lastParent"></param>
/// <param name="parents"></param>
/// <returns></returns>
private JObject ReturnParentObject(out string lastParent, string[] parents)
{
lastParent = null;
if(parents.Length > 0)
{
lastParent = parents[parents.Length - 1];
Array.Resize(ref parents, parents.Length - 1);
return GetValueOfKey<JObject>(lastParent, parents);
}
return root;
}
/// <summary>
/// Returns the value of the specified key from the specified parent(s) structure, which is split by the delimiter.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="parents"></param>
/// <returns></returns>
public T GetValueOfKey<T>(string key, string parents)
{
return GetValueOfKey<T>(key, parents.Split(delimiter));
}
/// <summary>
/// Returns the value of the specified key from the specified parent(s) structure.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="parents"></param>
/// <returns></returns>
public T GetValueOfKey<T>(string key, params string[] parents)
{
JObject parentObject = null;
for(int i = 0; i < parents.Length; i++)
parentObject = GetValueOfKey<JObject>(parents[i].Trim(), parentObject == null ? root : parentObject);
return GetValueOfKey<T>(key, parentObject == null ? root : parentObject);
}
/// <summary>
/// Returns the value of the specified key from the root structure.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
public T GetValueOfKey<T>(string key)
{
return GetValueOfKey<T>(key, root);
}
/// <summary>
/// Returns the value of the specified key from a given index in the structure.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="index"></param>
/// <returns></returns>
private T GetValueOfKey<T>(string key, JObject index)
{
JToken token = index.GetValue(key);
if (token != null)
return token.ToObject<T>();
foreach (var kvp in index)
if (kvp.Value is JObject)
{
T value = GetValueOfKey<T>(key, (JObject)kvp.Value);
if (value != null)
return value;
}
return default(T);
}
/// <summary>
/// Replaces an object specified by the given key and ensures object is replaced within the correct parent(s), which is split by the delimiter.
/// </summary>
/// <param name="key"></param>
/// <param name="replacement"></param>
/// <param name="parents"></param>
public void ReplaceObject(string key, JObject replacement, string parents)
{
ReplaceObject(key, root, replacement, parents.Split(delimiter));
}
/// <summary>
/// Replaces an object specified by the given key and ensures object is replaced within the correct parent(s).
/// </summary>
/// <param name="key"></param>
/// <param name="replacement"></param>
/// <param name="parents"></param>
public void ReplaceObject(string key, JObject replacement, params string[] parents)
{
ReplaceObject(key, root, replacement, parents);
}
/// <summary>
/// Replaces an object specified by the given key.
/// </summary>
/// <param name="key"></param>
/// <param name="replacement"></param>
public void ReplaceObject(string key, JObject replacement)
{
ReplaceObject(key, root, replacement);
}
/// <summary>
/// Replaces an object specified by the given key within the structure and updates changes to the root node.
/// </summary>
/// <param name="key"></param>
/// <param name="index"></param>
/// <param name="replacement"></param>
private void ReplaceObject(string key, JObject index, JObject replacement)
{
foreach (var kvp in index)
if (kvp.Value is JObject)
ReplaceObject(key, (JObject)kvp.Value, replacement);
JToken token = index.GetValue(key);
if (token != null)
{
JToken root = token.Root;
token.Replace(replacement);
this.root = (JObject)root;
}
}
/// <summary>
/// Replaces an object specified by the given key within the structure, ensuring object is replaced within the correct parent, and updates changes to the root node.
/// </summary>
/// <param name="key"></param>
/// <param name="index"></param>
/// <param name="replacement"></param>
/// <param name="parents"></param>
private void ReplaceObject(string key, JObject index, JObject replacement, params string[] parents)
{
foreach (var kvp in index)
if (kvp.Value is JObject)
{
bool valid = false;
foreach (string str in parents)
if (str.Trim() == kvp.Key)
valid = true;
if(valid)
ReplaceObject(key, (JObject)kvp.Value, replacement);
}
JToken token = index.GetValue(key);
if (token != null)
{
JToken root = token.Root;
token.Replace(replacement);
this.root = (JObject)root;
}
}
/// <summary>
/// Returns the root structure as JSON.
/// </summary>
/// <returns></returns>
public override string ToString()
{
return root.ToString();
}
/// <summary>
/// A ParentNotFoundException details that the supplied parent was not found within the structure.
/// </summary>
private class ParentNotFoundException : Exception
{
public ParentNotFoundException() { }
public ParentNotFoundException(string message) : base(message) { }
public ParentNotFoundException(string message, Exception inner) : base(message, inner) { }
}
}
Usage example:
Data data = new Data();
data.AddKeyWithValue("name", "foo");
data.AddChild("costs");
data.AddChild("attributes");
data.AddKeyWithValue("move", 1, "costs");
data.AddKeyWithValue("place", 2, "costs");
data.AddKeyWithValue("destroy", 3, "costs");
data.AddChild("movement", "costs");
data.AddKeyWithValue("slippery", false, "costs", "movement");
data.AddChild("movement", "attributes");
data.AddKeyWithValue("slippery", true, "attributes", "movement");
if(data.HasValue("move", "costs")) {
Debug.Log(data.GetValueOfKey<int>("move", "costs")
Debug.Log(data);
}
And its output:
1
{
"name": "foo",
"costs": {
"move": 1,
"place": 2,
"destroy": 3,
"movement": {
"slippery": false
}
},
"attributes": {
"movement": {
"slippery": true
}
}
}
Is there a way that i can refresh the HttpRuntime.Cache on Azure without having to Reboot the instance?
Thanks
When you're adding items to your cache, you should add them with a CacheDependency with a global key. This allows you to have your items expire after a given time but also to clear all items linked to this key.
Here is an example implementation of a method to clear all items (CacheProvider.cs):
/// <summary>
/// Caching provider
/// </summary>
public static class CacheProvider
{
const string CacheDependencyKey = "1FADE275-2C84-4a9b-B3E1-68ABB15E53C8";
static readonly object SyncRoot = new object();
/// <summary>
/// Gets an item from cache. If the item does not exist, one will be
/// created and added to the cache.
/// </summary>
/// <param name="key">Caching key</param>
/// <param name="valueFactory">Function to create the item of it does not exist in the cache.</param>
/// <param name="expiresAfter">Time after the item wille be removed from cache.</param>
public static TValue GetOrAdd<TValue>(string key, Func<TValue> valueFactory, TimeSpan expiresAfter)
{
object itemFromCache = HttpRuntime.Cache.Get(key);
if (itemFromCache == null)
{
lock (SyncRoot)
{
itemFromCache = HttpRuntime.Cache.Get(key);
if (itemFromCache == null)
{
TValue value = valueFactory();
if (value != null)
{
if (HttpRuntime.Cache[CacheDependencyKey] == null)
HttpRuntime.Cache[CacheDependencyKey] = string.Empty;
HttpRuntime.Cache.Add(key, value, new CacheDependency(null, new string[] { CacheDependencyKey }), DateTime.Now.Add(expiresAfter), Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);
}
return value;
}
}
}
return (TValue)itemFromCache;
}
/// <summary>
/// Invalidate all the items from the cache.
/// </summary>
public static void InvalidateCache()
{
HttpRuntime.Cache.Remove(CacheDependencyKey);
}
}
public void Clear()
{
var itemsToRemove = new List<string>();
var enumerator = HttpContext.Current.Cache.GetEnumerator();
while (enumerator.MoveNext())
{
itemsToRemove.Add(enumerator.Key.ToString());
}
foreach (string itemToRemove in itemsToRemove)
{
HttpContext.Current.Cache.Remove(itemToRemove);
}
}
I have created dictionary object
Dictionary<string, List<string>> dictionary =
new Dictionary<string,List<string>>();
I want to add string values to the list of string for a given single key.
If the key doesn't already exists then I have to add a new key. List<string> is not predefined, I mean I didn't create any list object and then supplied to dictionary.Add("key",Listname). How to create dynamically this list object in dictionary.Add("key",Listname) and then add strings to this list. If I have to add 100 keys then do I have to create 100 lists before executing dictionary.Add instruction and also do I have to pedefine the contents of this lists ?
Thank you.
Update: check for existence using TryGetValue to do only one lookup in the case where you have the list:
List<int> list;
if (!dictionary.TryGetValue("foo", out list))
{
list = new List<int>();
dictionary.Add("foo", list);
}
list.Add(2);
Original:
Check for existence and add once, then key into the dictionary to get the list and add to the list as normal:
var dictionary = new Dictionary<string, List<int>>();
if (!dictionary.ContainsKey("foo"))
dictionary.Add("foo", new List<int>());
dictionary["foo"].Add(42);
dictionary["foo"].AddRange(oneHundredInts);
Or List<string> as in your case.
As an aside, if you know how many items you are going to add to a dynamic collection such as List<T>, favour the constructor that takes the initial list capacity: new List<int>(100);.
This will grab the memory required to satisfy the specified capacity upfront, instead of grabbing small chunks every time it starts to fill up. You can do the same with dictionaries if you know you have 100 keys.
If I understood what you want:
dictionary.Add("key", new List<string>());
later...
dictionary["key"].Add("string to your list");
Dictionary<string, List<string>> dictionary = new Dictionary<string,List<string>>();
foreach(string key in keys) {
if(!dictionary.ContainsKey(key)) {
//add
dictionary.Add(key, new List<string>());
}
dictionary[key].Add("theString");
}
If the key doesn't exist, a new List is added (inside if). Else the key exists, so just add a new value to the List under that key.
You could use my implementation of a multimap, which derives from a Dictionary<K, List<V>>. It is not perfect, however it does a good job.
/// <summary>
/// Represents a collection of keys and values.
/// Multiple values can have the same key.
/// </summary>
/// <typeparam name="TKey">Type of the keys.</typeparam>
/// <typeparam name="TValue">Type of the values.</typeparam>
public class MultiMap<TKey, TValue> : Dictionary<TKey, List<TValue>>
{
public MultiMap()
: base()
{
}
public MultiMap(int capacity)
: base(capacity)
{
}
/// <summary>
/// Adds an element with the specified key and value into the MultiMap.
/// </summary>
/// <param name="key">The key of the element to add.</param>
/// <param name="value">The value of the element to add.</param>
public void Add(TKey key, TValue value)
{
List<TValue> valueList;
if (TryGetValue(key, out valueList)) {
valueList.Add(value);
} else {
valueList = new List<TValue>();
valueList.Add(value);
Add(key, valueList);
}
}
/// <summary>
/// Removes first occurence of an element with a specified key and value.
/// </summary>
/// <param name="key">The key of the element to remove.</param>
/// <param name="value">The value of the element to remove.</param>
/// <returns>true if the an element is removed;
/// false if the key or the value were not found.</returns>
public bool Remove(TKey key, TValue value)
{
List<TValue> valueList;
if (TryGetValue(key, out valueList)) {
if (valueList.Remove(value)) {
if (valueList.Count == 0) {
Remove(key);
}
return true;
}
}
return false;
}
/// <summary>
/// Removes all occurences of elements with a specified key and value.
/// </summary>
/// <param name="key">The key of the elements to remove.</param>
/// <param name="value">The value of the elements to remove.</param>
/// <returns>Number of elements removed.</returns>
public int RemoveAll(TKey key, TValue value)
{
List<TValue> valueList;
int n = 0;
if (TryGetValue(key, out valueList)) {
while (valueList.Remove(value)) {
n++;
}
if (valueList.Count == 0) {
Remove(key);
}
}
return n;
}
/// <summary>
/// Gets the total number of values contained in the MultiMap.
/// </summary>
public int CountAll
{
get
{
int n = 0;
foreach (List<TValue> valueList in Values) {
n += valueList.Count;
}
return n;
}
}
/// <summary>
/// Determines whether the MultiMap contains an element with a specific
/// key / value pair.
/// </summary>
/// <param name="key">Key of the element to search for.</param>
/// <param name="value">Value of the element to search for.</param>
/// <returns>true if the element was found; otherwise false.</returns>
public bool Contains(TKey key, TValue value)
{
List<TValue> valueList;
if (TryGetValue(key, out valueList)) {
return valueList.Contains(value);
}
return false;
}
/// <summary>
/// Determines whether the MultiMap contains an element with a specific value.
/// </summary>
/// <param name="value">Value of the element to search for.</param>
/// <returns>true if the element was found; otherwise false.</returns>
public bool Contains(TValue value)
{
foreach (List<TValue> valueList in Values) {
if (valueList.Contains(value)) {
return true;
}
}
return false;
}
}
Note that the Add method looks if a key is already present. If the key is new, a new list is created, the value is added to the list and the list is added to the dictionary. If the key was already present, the new value is added to the existing list.
Use NameValuedCollection.
Good starting point is here. Straight from the link.
System.Collections.Specialized.NameValueCollection myCollection
= new System.Collections.Specialized.NameValueCollection();
myCollection.Add(“Arcane”, “http://arcanecode.com”);
myCollection.Add(“PWOP”, “http://dotnetrocks.com”);
myCollection.Add(“PWOP”, “http://dnrtv.com”);
myCollection.Add(“PWOP”, “http://www.hanselminutes.com”);
myCollection.Add(“TWIT”, “http://www.twit.tv”);
myCollection.Add(“TWIT”, “http://www.twit.tv/SN”);
Though nearly the same as most of the other responses, I think this is the most efficient and concise way to implement it. Using TryGetValue is faster than using ContainsKey and reindexing into the dictionary as some other solutions have shown.
void Add(string key, string val)
{
List<string> list;
if (!dictionary.TryGetValue(someKey, out list))
{
values = new List<string>();
dictionary.Add(key, list);
}
list.Add(val);
}
When you add a string, do it differently depending on whether the key exists already or not. To add the string value for the key key:
List<string> list;
if (dictionary.ContainsKey(key)) {
list = dictionary[key];
} else {
list = new List<string>();
dictionary.Add(ley, list);
}
list.Add(value);
Instead of using a Dictionary, why not convert to an ILookup?
var myData = new[]{new {a=1,b="frog"}, new {a=1,b="cat"}, new {a=2,b="giraffe"}};
ILookup<int,string> lookup = myData.ToLookup(x => x.a, x => x.b);
IEnumerable<string> allOnes = lookup[1]; //enumerable of 2 items, frog and cat
An ILookup is an immutable data structure that allows multiple values per key. Probably not much use if you need to add items at different times, but if you have all your data up-front, this is definitely the way to go.
Here are many variations of the one answer :) My is another one and it uses extension mechanism as comfortable way to execute (handy):
public static void AddToList<T, U>(this IDictionary<T, List<U>> dict, T key, U elementToList)
{
List<U> list;
bool exists = dict.TryGetValue(key, out list);
if (exists)
{
dict[key].Add(elementToList);
}
else
{
dict[key] = new List<U>();
dict[key].Add(elementToList);
}
}
Then you use it as follows:
Dictionary<int, List<string>> dict = new Dictionary<int, List<string>>();
dict.AddToList(4, "test1");
dict.AddToList(4, "test2");
dict.AddToList(4, "test3");
dict.AddToList(5, "test4");
There is a NuGet package Microsoft Experimental Collections that contains a class MultiValueDictionary which does exactly what you need.
Here is a blog post of the creator of the package that describes it further.
Here is another blog post if you're feeling curious.
Example Usage:
MultiDictionary<string, int> myDictionary = new MultiDictionary<string, int>();
myDictionary.Add("key", 1);
myDictionary.Add("key", 2);
myDictionary.Add("key", 3);
//myDictionary["key"] now contains the values 1, 2, and 3
I was trying to add List to existing key in dictionary and reached the following solution:
Dictionary<string,List<string>> NewParent = new Dictionary<string,List<string>>();
child = new List<string> ();
child.Add('SomeData');
NewParent["item1"].AddRange(child);
It will not show any exception and won't replace previous values.
There is a 'one-command-line' way to do this using AddOrUpdate from ConcurrentDictionary:
using System.Linq;
using System.Collections.Generic;
using System.Collections.Concurrent;
...
var dictionary = new ConcurrentDictionary<string, IEnumerable<string>>();
var itemToAdd = "item to add to key-list";
dictionary.AddOrUpdate("key", new[]{itemToAdd}, (key,list) => list.Append(itemToAdd));
// If "key" doesn't exist, creates it with a list containing itemToAdd as value
// If "key" exists, adds item to already existent list (third parameter)
I'm improving on this answer with a couple of extension methods I've wrote. The first one is similar to how #Bronek wrote it, just a bit more concise. Simply put, if a key exists, it inserts into the already existing list (assuming it was initialized to begin with). Otherwise, it adds to the list.
public static void AddToList<K, V>(this Dictionary<K, List<V>> multiValueDictionary,
K key,
V value)
{
if (multiValueDictionary.TryGetValue(key, out List<V> lst))
lst.Add(value);
else
multiValueDictionary.Add(key, new List<V> { value });
}
This second function builds off the previous. In System.Linq, the extension method ToDictionary which can transform any IEnumerable into a Dictionary. But what if you have the above scenario where you want to store multiple values for a single key? Well then the below extension will work!
public static Dictionary<K, List<V>> ToDictionaryValueList<T, K, V>(this IEnumerable<T> values, Func<T, K> keySelector, Func<T, V> elementSelector)
{
var tmp = new Dictionary<K, List<V>>();
foreach (var val in values)
tmp.AddToList(keySelector(val), elementSelector(val));
return tmp;
// NOTE: You can also use the below IEnumerable extensions to accomplish the same goal, but the above might be (?) more efficient, not sure
// return values
// .GroupBy(v => keySelector(v))
// .ToDictionary(v => v.Key, v => v.ToList());
}
With the above two, its now easy to transform any IEnumerable into one of these dictionaries.
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
List<Person> test = new List<Person>
{
new Person { Name = "Bob", Age = 22 },
new Person { Name = "Bob", Age = 28 },
new Person { Name = "Sally", Age = 22 },
new Person { Name = "Sally", Age = 22 },
new Person { Name = "Jill", Age = 22 },
}
// Aggregate each person
Dictionary<string, List<int>> results = test.ToDictionaryValueList((p) => p.Name, (p) => p.Age);
// Use the AddToList extension method to add more values as neeeded
results.AddToList("Jill", 23);
One thing to consider is that duplicate values aren't handled, as expected from a standard List. You'll want to make extension methods for different collections like HashSet if you need it.
I have been learning the basics of generics in .NET. However, I don't see the generic equivalent of Hashtable. Please share some sample C# code for creating generic hashtable classes.
Dictionary<TKey, TValue>
Note that Dictionary is not a 100% drop in replacement for HashTable.
There is a slight difference in the way they handle NULLs.
The dictionary will throw an exception if you try to reference a key that doesn't exist. The HashTable will just return null.
The reason is that the value might be a value type, which cannot be null. In a Hashtable the value was always Object, so returning null was at least possible.
The generic version of Hashtable class is System.Collections.Generic.Dictionary class.
Sample code:
Dictionary<int, string> numbers = new Dictionary<int, string>( );
numbers.Add(1, "one");
numbers.Add(2, "two");
// Display all key/value pairs in the Dictionary.
foreach (KeyValuePair<int, string> kvp in numbers)
{
Console.WriteLine("Key: " + kvp.Key + "\tValue: " + kvp.Value);
}
The generic version of a Hashtable is the Dictionary<TKey,TValue> class (link). Here is some sample code translated from using a Hashtable into the most direct equivalent of Dictionary (argument checking removed for sake of brevity)
public HashTable Create(int[] keys, string[] values) {
HashTable table = new HashTable();
for ( int i = 0; i < keys.Length; i++ ) {
table[keys[i]] = values[i];
}
return table;
}
public Dictionary<object,object> Create(int[] keys, string[] values) {
Dictionary<object,object> map = Dictionary<object,object>();
for ( int i = 0; i < keys.Length; i++) {
map[keys[i]] = values[i];
}
return map;
}
That's a fairly direct translation. But the problem is that this does not actually take advantage of the type safe features of generics. The second function could be written as follows and be much more type safe and inccur no boxing overhead
public Dictionary<int,string> Create(int[] keys, string[] values) {
Dictionary<int,string> map = Dictionary<int,string>();
for ( int i = 0; i < keys.Length; i++) {
map[keys[i]] = values[i];
}
return map;
}
Even better. Here's a completely generic version
public Dictionary<TKey,TValue> Create<TKey,TValue>(TKey[] keys, TValue[] values) {
Dictionary<TKey,TValue> map = Dictionary<TKey,TValue>();
for ( int i = 0; i < keys.Length; i++) {
map[keys[i]] = values[i];
}
return map;
}
And one that is even further flexible (thanks Joel for pointing out I missed this)
public Dictionary<TKey,TValue> Create<TKey,TValue>(
IEnumerable<TKey> keys,
IEnumerable<TValue> values) {
Dictionary<TKey,TValue> map = Dictionary<TKey,TValue>();
using ( IEnumerater<TKey> keyEnum = keys.GetEnumerator() )
using ( IEnumerator<TValue> valueEnum = values.GetEnumerator()) {
while (keyEnum.MoveNext() && valueEnum.MoveNext() ) {
map[keyEnum.Current] = valueEnum.Current;
}
}
return map;
}
For those who are interested, I created a generic Hashtable wrapper class, which is useful for enforcing type safety and can be passed as a generic IDictionary, ICollection and IEnumerable type, whereas the non-generic Hashtable cannot. Below is the implementation.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Common.Collections.Generic
{
public class Hashtable<TKey, TValue> : IDictionary<TKey, TValue>
, ICollection<KeyValuePair<TKey, TValue>>
, IEnumerable<KeyValuePair<TKey, TValue>>
, IDictionary
, ICollection
, IEnumerable
{
protected Hashtable _items;
/// <summary>
/// Initializes a new, empty instance of the Hashtable class using the default initial capacity, load factor, hash code provider, and comparer.
/// </summary>
public Hashtable()
{
_items = new Hashtable();
}
/// <summary>
/// Initializes a new, empty instance of the Hashtable class using the specified initial capacity, and the default load factor, hash code provider, and comparer.
/// </summary>
/// <param name="capacity">The approximate number of elements that the Hashtable object can initially contain. </param>
public Hashtable(int capacity)
{
_items = new Hashtable(capacity);
}
/// <summary>
/// Actual underlying hashtable object that contains the elements.
/// </summary>
public Hashtable Items { get { return _items; } }
/// <summary>
/// Adds an element with the specified key and value into the Hashtable.
/// </summary>
/// <param name="key">Key of the new element to add.</param>
/// <param name="value">Value of the new elment to add.</param>
public void Add(TKey key, TValue value)
{
_items.Add(key, value);
}
/// <summary>
/// Adds an element with the specified key and value into the Hashtable.
/// </summary>
/// <param name="item">Item containing the key and value to add.</param>
public void Add(KeyValuePair<TKey, TValue> item)
{
_items.Add(item.Key, item.Value);
}
void IDictionary.Add(object key, object value)
{
this.Add((TKey)key, (TValue)value);
}
/// <summary>
/// Add a list of key/value pairs to the hashtable.
/// </summary>
/// <param name="collection">List of key/value pairs to add to hashtable.</param>
public void AddRange(IEnumerable<KeyValuePair<TKey, TValue>> collection)
{
foreach (var item in collection)
_items.Add(item.Key, item.Value);
}
/// <summary>
/// Determines whether the Hashtable contains a specific key.
/// </summary>
/// <param name="key">Key to locate.</param>
/// <returns>True if key is found, otherwise false.</returns>
public bool ContainsKey(TKey key)
{
return _items.ContainsKey(key);
}
/// <summary>
/// Determines whether the Hashtable contains a specific key.
/// </summary>
/// <param name="item">Item containing the key to locate.</param>
/// <returns>True if item.Key is found, otherwise false.</returns>
public bool Contains(KeyValuePair<TKey, TValue> item)
{
return _items.ContainsKey(item.Key);
}
bool IDictionary.Contains(object key)
{
return this.ContainsKey((TKey)key);
}
/// <summary>
/// Gets an ICollection containing the keys in the Hashtable.
/// </summary>
public ICollection<TKey> Keys
{
get { return _items.ToList<TKey>(); }
}
ICollection IDictionary.Keys
{
get { return this.Keys.ToList(); }
}
/// <summary>
/// Gets the value associated with the specified key.
/// </summary>
/// <param name="key">The key of the value to get.</param>
/// <param name="value">When this method returns, contains the value associated with the specified key,
/// if the key is found; otherwise, the default value for the type of the value parameter. This parameter
/// is passed uninitialized.</param>
/// <returns>true if the hashtable contains an element with the specified key, otherwise false.</returns>
public bool TryGetValue(TKey key, out TValue value)
{
value = (TValue)_items[key];
return (value != null);
}
/// <summary>
/// Gets an ICollection containing the values in the Hashtable.
/// </summary>
public ICollection<TValue> Values
{
get { return _items.Values.ToList<TValue>(); }
}
ICollection IDictionary.Values
{
get { return this.Values.ToList(); }
}
/// <summary>
/// Gets or sets the value associated with the specified key.
/// </summary>
/// <param name="key">The key whose value to get or set. </param>
/// <returns>The value associated with the specified key. If the specified key is not found,
/// attempting to get it returns null, and attempting to set it creates a new element using the specified key.</returns>
public TValue this[TKey key]
{
get
{
return (TValue)_items[key];
}
set
{
_items[key] = value;
}
}
/// <summary>
/// Removes all elements from the Hashtable.
/// </summary>
public void Clear()
{
_items.Clear();
}
/// <summary>
/// Copies all key/value pairs in the hashtable to the specified array.
/// </summary>
/// <param name="array">Object array to store objects of type "KeyValuePair<TKey, TValue>"</param>
/// <param name="arrayIndex">Starting index to store objects into array.</param>
public void CopyTo(Array array, int arrayIndex)
{
_items.CopyTo(array, arrayIndex);
}
/// <summary>
/// Copies all key/value pairs in the hashtable to the specified array.
/// </summary>
/// <param name="array">Object array to store objects of type "KeyValuePair<TKey, TValue>"</param>
/// <param name="arrayIndex">Starting index to store objects into array.</param>
public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
_items.CopyTo(array, arrayIndex);
}
/// <summary>
/// Gets the number of key/value pairs contained in the Hashtable.
/// </summary>
public int Count
{
get { return _items.Count; }
}
/// <summary>
/// Gets a value indicating whether the Hashtable has a fixed size.
/// </summary>
public bool IsFixedSize
{
get { return _items.IsFixedSize; }
}
/// <summary>
/// Gets a value indicating whether the Hashtable is read-only.
/// </summary>
public bool IsReadOnly
{
get { return _items.IsReadOnly; }
}
/// <summary>
/// Gets a value indicating whether access to the Hashtable is synchronized (thread safe).
/// </summary>
public bool IsSynchronized
{
get { return _items.IsSynchronized; }
}
/// <summary>
/// Gets an object that can be used to synchronize access to the Hashtable.
/// </summary>
public object SyncRoot
{
get { return _items.SyncRoot; }
}
/// <summary>
/// Removes the element with the specified key from the Hashtable.
/// </summary>
/// <param name="key">Key of the element to remove.</param>
public void Remove(TKey key)
{
_items.Remove(key);
}
/// <summary>
/// Removes the element with the specified key from the Hashtable.
/// </summary>
/// <param name="item">Item containing the key of the element to remove.</param>
public void Remove(KeyValuePair<TKey, TValue> item)
{
this.Remove(item.Key);
}
bool IDictionary<TKey, TValue>.Remove(TKey key)
{
var numValues = _items.Count;
_items.Remove(key);
return numValues > _items.Count;
}
bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item)
{
var numValues = _items.Count;
_items.Remove(item.Key);
return numValues > _items.Count;
}
void IDictionary.Remove(object key)
{
_items.Remove(key);
}
/// <summary>
/// Returns an enumerator that iterates through the hashtable.
/// </summary>
/// <returns>An enumerator for a list of key/value pairs.</returns>
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
foreach (DictionaryEntry? item in _items)
yield return new KeyValuePair<TKey, TValue>((TKey)item.Value.Key, (TValue)item.Value.Value);
}
/// <summary>
/// Returns an enumerator that iterates through the hashtable.
/// </summary>
/// <returns>An enumerator for a list of key/value pairs as generic objects.</returns>
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
IDictionaryEnumerator IDictionary.GetEnumerator()
{
// Very old enumerator that no one uses anymore, not supported.
throw new NotImplementedException();
}
object IDictionary.this[object key]
{
get
{
return _items[(TKey)key];
}
set
{
_items[(TKey)key] = value;
}
}
}
}
I have done some testing of this Hashtable vs Dictionary and found the two perform about the same when used with a string key and string value pair, except the Hashtable seems to use less memory. The results of my test are as follows:
TestInitialize Dictionary_50K_Hashtable
Number objects 50000, memory usage 905164
Insert, 22 milliseconds.
A search not found, 0 milliseconds.
Search found, 0 milliseconds.
Remove, 0 milliseconds.
Search found or not found, 0 milliseconds.
TestCleanup Dictionary_50K_Hashtable
TestInitialize Dictionary_50K_Dictionary
Number objects 50000, memory usage 1508316
Insert, 16 milliseconds.
A search not found, 0 milliseconds.
Search found, 0 milliseconds.
Remove, 0 milliseconds.
Search found or not found, 0 milliseconds.
TestCleanup Dictionary_50K_Dictionary
The generic version of System.Collection.Hashtable is System.Collections.Generic.Dictionary<TKey, TValue>.
It's easy to get the value of a key from a .NET generic Dictionary:
Dictionary<int, string> greek = new Dictionary<int, string>();
greek.Add(1, "Alpha");
greek.Add(2, "Beta");
string secondGreek = greek[2]; // Beta
But trying to get the keys given a value is not as straightforward because there could be multiple keys:
int[] betaKeys = greek.WhatDoIPutHere("Beta"); // expecting single 2
Okay, here's the multiple bidirectional version:
using System;
using System.Collections.Generic;
using System.Text;
class BiDictionary<TFirst, TSecond>
{
IDictionary<TFirst, IList<TSecond>> firstToSecond = new Dictionary<TFirst, IList<TSecond>>();
IDictionary<TSecond, IList<TFirst>> secondToFirst = new Dictionary<TSecond, IList<TFirst>>();
private static IList<TFirst> EmptyFirstList = new TFirst[0];
private static IList<TSecond> EmptySecondList = new TSecond[0];
public void Add(TFirst first, TSecond second)
{
IList<TFirst> firsts;
IList<TSecond> seconds;
if (!firstToSecond.TryGetValue(first, out seconds))
{
seconds = new List<TSecond>();
firstToSecond[first] = seconds;
}
if (!secondToFirst.TryGetValue(second, out firsts))
{
firsts = new List<TFirst>();
secondToFirst[second] = firsts;
}
seconds.Add(second);
firsts.Add(first);
}
// Note potential ambiguity using indexers (e.g. mapping from int to int)
// Hence the methods as well...
public IList<TSecond> this[TFirst first]
{
get { return GetByFirst(first); }
}
public IList<TFirst> this[TSecond second]
{
get { return GetBySecond(second); }
}
public IList<TSecond> GetByFirst(TFirst first)
{
IList<TSecond> list;
if (!firstToSecond.TryGetValue(first, out list))
{
return EmptySecondList;
}
return new List<TSecond>(list); // Create a copy for sanity
}
public IList<TFirst> GetBySecond(TSecond second)
{
IList<TFirst> list;
if (!secondToFirst.TryGetValue(second, out list))
{
return EmptyFirstList;
}
return new List<TFirst>(list); // Create a copy for sanity
}
}
class Test
{
static void Main()
{
BiDictionary<int, string> greek = new BiDictionary<int, string>();
greek.Add(1, "Alpha");
greek.Add(2, "Beta");
greek.Add(5, "Beta");
ShowEntries(greek, "Alpha");
ShowEntries(greek, "Beta");
ShowEntries(greek, "Gamma");
}
static void ShowEntries(BiDictionary<int, string> dict, string key)
{
IList<int> values = dict[key];
StringBuilder builder = new StringBuilder();
foreach (int value in values)
{
if (builder.Length != 0)
{
builder.Append(", ");
}
builder.Append(value);
}
Console.WriteLine("{0}: [{1}]", key, builder);
}
}
As everyone else has said, there's no mapping within a dictionary from value to key.
I've just noticed you wanted to map to from value to multiple keys - I'm leaving this solution here for the single value version, but I'll then add another answer for a multi-entry bidirectional map.
The normal approach to take here is to have two dictionaries - one mapping one way and one the other. Encapsulate them in a separate class, and work out what you want to do when you have duplicate key or value (e.g. throw an exception, overwrite the existing entry, or ignore the new entry). Personally I'd probably go for throwing an exception - it makes the success behaviour easier to define. Something like this:
using System;
using System.Collections.Generic;
class BiDictionary<TFirst, TSecond>
{
IDictionary<TFirst, TSecond> firstToSecond = new Dictionary<TFirst, TSecond>();
IDictionary<TSecond, TFirst> secondToFirst = new Dictionary<TSecond, TFirst>();
public void Add(TFirst first, TSecond second)
{
if (firstToSecond.ContainsKey(first) ||
secondToFirst.ContainsKey(second))
{
throw new ArgumentException("Duplicate first or second");
}
firstToSecond.Add(first, second);
secondToFirst.Add(second, first);
}
public bool TryGetByFirst(TFirst first, out TSecond second)
{
return firstToSecond.TryGetValue(first, out second);
}
public bool TryGetBySecond(TSecond second, out TFirst first)
{
return secondToFirst.TryGetValue(second, out first);
}
}
class Test
{
static void Main()
{
BiDictionary<int, string> greek = new BiDictionary<int, string>();
greek.Add(1, "Alpha");
greek.Add(2, "Beta");
int x;
greek.TryGetBySecond("Beta", out x);
Console.WriteLine(x);
}
}
Dictionaries aren't really meant to work like this, because while uniqueness of keys is guaranteed, uniqueness of values isn't. So e.g. if you had
var greek = new Dictionary<int, string> { { 1, "Alpha" }, { 2, "Alpha" } };
What would you expect to get for greek.WhatDoIPutHere("Alpha")?
Therefore you can't expect something like this to be rolled into the framework. You'd need your own method for your own unique uses---do you want to return an array (or IEnumerable<T>)? Do you want to throw an exception if there are multiple keys with the given value? What about if there are none?
Personally I'd go for an enumerable, like so:
IEnumerable<TKey> KeysFromValue<TKey, TValue>(this Dictionary<TKey, TValue> dict, TValue val)
{
if (dict == null)
{
throw new ArgumentNullException("dict");
}
return dict.Keys.Where(k => dict[k] == val);
}
var keys = greek.KeysFromValue("Beta");
int exceptionIfNotExactlyOne = greek.KeysFromValue("Beta").Single();
Maybe the easiest way to do it, without Linq, can be to loop over the pairs:
int betaKey;
foreach (KeyValuePair<int, string> pair in lookup)
{
if (pair.Value == value)
{
betaKey = pair.Key; // Found
break;
}
}
betaKey = -1; // Not found
If you had Linq, it could have done easily this way:
int betaKey = greek.SingleOrDefault(x => x.Value == "Beta").Key;
A dictionary doesn't keep an hash of the values, only the keys, so any search over it using a value is going to take at least linear time. Your best bet is to simply iterate over the elements in the dictionary and keep track of the matching keys or switch to a different data structure, perhaps maintain two dictionary mapping key->value and value->List_of_keys. If you do the latter you will trade storage for look up speed. It wouldn't take much to turn #Cybis example into such a data structure.
As I wanted a full fledged BiDirectional Dictionary (and not only a Map), I added the missing functions to make it an IDictionary compatible class. This is based on the version with unique Key-Value Pairs. Here's the file if desired (Most work was the XMLDoc through):
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Common
{
/// <summary>Represents a bidirectional collection of keys and values.</summary>
/// <typeparam name="TFirst">The type of the keys in the dictionary</typeparam>
/// <typeparam name="TSecond">The type of the values in the dictionary</typeparam>
[System.Runtime.InteropServices.ComVisible(false)]
[System.Diagnostics.DebuggerDisplay("Count = {Count}")]
//[System.Diagnostics.DebuggerTypeProxy(typeof(System.Collections.Generic.Mscorlib_DictionaryDebugView<,>))]
//[System.Reflection.DefaultMember("Item")]
public class BiDictionary<TFirst, TSecond> : Dictionary<TFirst, TSecond>
{
IDictionary<TSecond, TFirst> _ValueKey = new Dictionary<TSecond, TFirst>();
/// <summary> PropertyAccessor for Iterator over KeyValue-Relation </summary>
public IDictionary<TFirst, TSecond> KeyValue => this;
/// <summary> PropertyAccessor for Iterator over ValueKey-Relation </summary>
public IDictionary<TSecond, TFirst> ValueKey => _ValueKey;
#region Implemented members
/// <Summary>Gets or sets the value associated with the specified key.</Summary>
/// <param name="key">The key of the value to get or set.</param>
/// <Returns>The value associated with the specified key. If the specified key is not found,
/// a get operation throws a <see cref="KeyNotFoundException"/>, and
/// a set operation creates a new element with the specified key.</Returns>
/// <exception cref="T:System.ArgumentNullException"><paramref name="key"/> is null.</exception>
/// <exception cref="T:System.Collections.Generic.KeyNotFoundException">
/// The property is retrieved and <paramref name="key"/> does not exist in the collection.</exception>
/// <exception cref="T:System.ArgumentException"> An element with the same key already
/// exists in the <see cref="ValueKey"/> <see cref="Dictionary<TFirst,TSecond>"/>.</exception>
public new TSecond this[TFirst key]
{
get { return base[key]; }
set { _ValueKey.Remove(base[key]); base[key] = value; _ValueKey.Add(value, key); }
}
/// <Summary>Gets or sets the key associated with the specified value.</Summary>
/// <param name="val">The value of the key to get or set.</param>
/// <Returns>The key associated with the specified value. If the specified value is not found,
/// a get operation throws a <see cref="KeyNotFoundException"/>, and
/// a set operation creates a new element with the specified value.</Returns>
/// <exception cref="T:System.ArgumentNullException"><paramref name="val"/> is null.</exception>
/// <exception cref="T:System.Collections.Generic.KeyNotFoundException">
/// The property is retrieved and <paramref name="val"/> does not exist in the collection.</exception>
/// <exception cref="T:System.ArgumentException"> An element with the same value already
/// exists in the <see cref="KeyValue"/> <see cref="Dictionary<TFirst,TSecond>"/>.</exception>
public TFirst this[TSecond val]
{
get { return _ValueKey[val]; }
set { base.Remove(_ValueKey[val]); _ValueKey[val] = value; base.Add(value, val); }
}
/// <Summary>Adds the specified key and value to the dictionary.</Summary>
/// <param name="key">The key of the element to add.</param>
/// <param name="value">The value of the element to add.</param>
/// <exception cref="T:System.ArgumentNullException"><paramref name="key"/> or <paramref name="value"/> is null.</exception>
/// <exception cref="T:System.ArgumentException">An element with the same key or value already exists in the <see cref="Dictionary<TFirst,TSecond>"/>.</exception>
public new void Add(TFirst key, TSecond value) {
base.Add(key, value);
_ValueKey.Add(value, key);
}
/// <Summary>Removes all keys and values from the <see cref="Dictionary<TFirst,TSecond>"/>.</Summary>
public new void Clear() { base.Clear(); _ValueKey.Clear(); }
/// <Summary>Determines whether the <see cref="Dictionary<TFirst,TSecond>"/> contains the specified
/// KeyValuePair.</Summary>
/// <param name="item">The KeyValuePair to locate in the <see cref="Dictionary<TFirst,TSecond>"/>.</param>
/// <Returns>true if the <see cref="Dictionary<TFirst,TSecond>"/> contains an element with
/// the specified key which links to the specified value; otherwise, false.</Returns>
/// <exception cref="T:System.ArgumentNullException"><paramref name="item"/> is null.</exception>
public bool Contains(KeyValuePair<TFirst, TSecond> item) => base.ContainsKey(item.Key) & _ValueKey.ContainsKey(item.Value);
/// <Summary>Removes the specified KeyValuePair from the <see cref="Dictionary<TFirst,TSecond>"/>.</Summary>
/// <param name="item">The KeyValuePair to remove.</param>
/// <Returns>true if the KeyValuePair is successfully found and removed; otherwise, false. This
/// method returns false if <paramref name="item"/> is not found in the <see cref="Dictionary<TFirst,TSecond>"/>.</Returns>
/// <exception cref="T:System.ArgumentNullException"><paramref name="item"/> is null.</exception>
public bool Remove(KeyValuePair<TFirst, TSecond> item) => base.Remove(item.Key) & _ValueKey.Remove(item.Value);
/// <Summary>Removes the value with the specified key from the <see cref="Dictionary<TFirst,TSecond>"/>.</Summary>
/// <param name="key">The key of the element to remove.</param>
/// <Returns>true if the element is successfully found and removed; otherwise, false. This
/// method returns false if <paramref name="key"/> is not found in the <see cref="Dictionary<TFirst,TSecond>"/>.</Returns>
/// <exception cref="T:System.ArgumentNullException"><paramref name="key"/> is null.</exception>
public new bool Remove(TFirst key) => _ValueKey.Remove(base[key]) & base.Remove(key);
/// <Summary>Gets the key associated with the specified value.</Summary>
/// <param name="value">The value of the key to get.</param>
/// <param name="key">When this method returns, contains the key associated with the specified value,
/// if the value is found; otherwise, the default value for the type of the key parameter.
/// This parameter is passed uninitialized.</param>
/// <Returns>true if <see cref="ValueKey"/> contains an element with the specified value;
/// otherwise, false.</Returns>
/// <exception cref="T:System.ArgumentNullException"><paramref name="value"/> is null.</exception>
public bool TryGetValue(TSecond value, out TFirst key) => _ValueKey.TryGetValue(value, out key);
#endregion
}
}
revised: okay to have some kind of find you would need something other than dictionary, since if you think about it dictionary are one way keys. that is, the values might not be unique
that said it looks like you're using c#3.0 so you might not have to resort to looping and could use something like:
var key = (from k in yourDictionary where string.Compare(k.Value, "yourValue", true) == 0 select k.Key).FirstOrDefault();
Dictionary class is not optimized for this case, but if you really wanted to do it (in C# 2.0), you can do:
public List<TKey> GetKeysFromValue<TKey, TVal>(Dictionary<TKey, TVal> dict, TVal val)
{
List<TKey> ks = new List<TKey>();
foreach(TKey k in dict.Keys)
{
if (dict[k] == val) { ks.Add(k); }
}
return ks;
}
I prefer the LINQ solution for elegance, but this is the 2.0 way.
Can't you create a subclass of Dictionary which has that functionality?
public class MyDict < TKey, TValue > : Dictionary < TKey, TValue >
{
private Dictionary < TValue, TKey > _keys;
public TValue this[TKey key]
{
get
{
return base[key];
}
set
{
base[key] = value;
_keys[value] = key;
}
}
public MyDict()
{
_keys = new Dictionary < TValue, TKey >();
}
public TKey GetKeyFromValue(TValue value)
{
return _keys[value];
}
}
EDIT: Sorry, didn't get code right first time.
The "simple" bidirectional dictionary solution proposed here is complex and may be be difficult to understand, maintain or extend. Also the original question asked for "the key for a value", but clearly there could be multiple keys (I've since edited the question). The whole approach is rather suspicious.
Software changes. Writing code that is easy to maintain should be given priority other "clever" complex workarounds. The way to get keys back from values in a dictionary is to loop. A dictionary isn't designed to be bidirectional.
Use LINQ to do a reverse Dictionary<K, V> lookup. But keep in mind that the values in your Dictionary<K, V> values may not be distinct.
Demonstration:
using System;
using System.Collections.Generic;
using System.Linq;
class ReverseDictionaryLookupDemo
{
static void Main()
{
var dict = new Dictionary<int, string>();
dict.Add(4, "Four");
dict.Add(5, "Five");
dict.Add(1, "One");
dict.Add(11, "One"); // duplicate!
dict.Add(3, "Three");
dict.Add(2, "Two");
dict.Add(44, "Four"); // duplicate!
Console.WriteLine("\n== Enumerating Distinct Values ==");
foreach (string value in dict.Values.Distinct())
{
string valueString =
String.Join(", ", GetKeysFromValue(dict, value));
Console.WriteLine("{0} => [{1}]", value, valueString);
}
}
static List<int> GetKeysFromValue(Dictionary<int, string> dict, string value)
{
// Use LINQ to do a reverse dictionary lookup.
// Returns a 'List<T>' to account for the possibility
// of duplicate values.
return
(from item in dict
where item.Value.Equals(value)
select item.Key).ToList();
}
}
Expected Output:
== Enumerating Distinct Values ==
Four => [4, 44]
Five => [5]
One => [1, 11]
Three => [3]
Two => [2]
Dictionary<string, string> dic = new Dictionary<string, string>();
dic["A"] = "Ahmed";
dic["B"] = "Boys";
foreach (string mk in dic.Keys)
{
if(dic[mk] == "Ahmed")
{
Console.WriteLine("The key that contains \"Ahmed\" is " + mk);
}
}
Many of these answers are now outdated, here is a modern C# approach, using LINQ
Since values aren't necessarily unique, you may get multiple results. You can return an IEnumerable<KeyValuePair<int, string>>:
var betaKeys = greek.Where(x => x.Value == "beta");
To transform this into an IEnumerable<int> type, just use .Select():
var betaKeys = greek.Where(x => x.Value == "beta").Select(x => x.Key);
As a twist of the accepted answer (https://stackoverflow.com/a/255638/986160) assuming that the keys will be associated with signle values in the dictionary. Similar to (https://stackoverflow.com/a/255630/986160) but a bit more elegant. The novelty is in that the consuming class can be used as an enumeration alternative (but for strings too) and that the dictionary implements IEnumerable.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace MyApp.Dictionaries
{
class BiDictionary<TFirst, TSecond> : IEnumerable
{
IDictionary<TFirst, TSecond> firstToSecond = new Dictionary<TFirst, TSecond>();
IDictionary<TSecond, TFirst> secondToFirst = new Dictionary<TSecond, TFirst>();
public void Add(TFirst first, TSecond second)
{
firstToSecond.Add(first, second);
secondToFirst.Add(second, first);
}
public TSecond this[TFirst first]
{
get { return GetByFirst(first); }
}
public TFirst this[TSecond second]
{
get { return GetBySecond(second); }
}
public TSecond GetByFirst(TFirst first)
{
return firstToSecond[first];
}
public TFirst GetBySecond(TSecond second)
{
return secondToFirst[second];
}
public IEnumerator GetEnumerator()
{
return GetFirstEnumerator();
}
public IEnumerator GetFirstEnumerator()
{
return firstToSecond.GetEnumerator();
}
public IEnumerator GetSecondEnumerator()
{
return secondToFirst.GetEnumerator();
}
}
}
And as a consuming class you could have
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MyApp.Dictionaries
{
class Greek
{
public static readonly string Alpha = "Alpha";
public static readonly string Beta = "Beta";
public static readonly string Gamma = "Gamma";
public static readonly string Delta = "Delta";
private static readonly BiDictionary<int, string> Dictionary = new BiDictionary<int, string>();
static Greek() {
Dictionary.Add(1, Alpha);
Dictionary.Add(2, Beta);
Dictionary.Add(3, Gamma);
Dictionary.Add(4, Delta);
}
public static string getById(int id){
return Dictionary.GetByFirst(id);
}
public static int getByValue(string value)
{
return Dictionary.GetBySecond(value);
}
}
}
Then layman's solution
A function similar to the one below could be written to make such a dictionary:
public Dictionary<TValue, TKey> Invert(Dictionary<TKey, TValue> dict) {
Dictionary<TValue, TKey> ret = new Dictionary<TValue, TKey>();
foreach (var kvp in dict) {ret[kvp.value] = kvp.key;} return ret; }
Probably, you need a bidirectional dictionary. In my mind, BidirectionalDictionary is the best realization of a bidirectional dictionary. It just provides access to an inverse O(1) dictionary.
var biDictionary = new BidirectionalDictionary<T1,T2> { ... };
This realization, for example, has no indexations problems when TKey equals TValue:
var capital = countryCapitalDictionary["Italy"]; // "Rome"
var country = countryCapitalDictionary.Inverse["Rome"]; // "Italy"
Changing the dictionary causes the reverse dictionary to be changed safely (as well as vice versa):
countryCapitalDictionary.Clear(); // equals countryCapitalDictionary.Inverse.Clear();
var containsCapital = countryCapitalDictionary.ContainsKey("Italy"); // false
var containsCountry = countryCapitalDictionary.Inverse.ContainsKey("Rome"); // false
Also, this library supports a read-only bidirectional dictionary:
var readOnlyBiDictionary = new ReadOnlyBidurectionalDictionary<T1, T2>(biDictionary);
You can use it via the package.