可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
It\'s easy to get the value of a key from a .Net 2.0 generic Dictionary:
Dictionary<int, string> greek = new Dictionary<int, string>();
greek.Add(1, \"Alpha\");
greek.Add(2, \"Beta\");
string secondGreek = greek[2]; // Beta
But is there a simple way to get the key of a value?
int[] betaKeys = greek.WhatDoIPutHere(\"Beta\"); // expecting single 2
回答1:
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);
}
}
回答2:
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);
}
}
回答3:
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();
回答4:
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;
回答5:
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.
回答6:
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
}
}
回答7:
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();
回答8:
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.
回答9:
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.
回答10:
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.
回答11:
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]
回答12:
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);
}
}
回答13:
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);
}
}
}
回答14:
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; }