C
C#9mo ago
RumTery

Is there some standard KeyValue collection allowing adding by value and retrive by key, not dict?

Something like this
public interface IKeyd<TKey> where TKey: IEquatable<TKey>
{
public TKey Key { get; }
}
public class KeyValueCollection<TKey, TValue> where TValue: IKeyd<TKey> where TKey: IEquatable<TKey>
{
private Dictionary<TKey, TValue> _keyValues = new();
public void Add(TValue value)
{
_keyValues.Add(value.Key, value);
}
public bool TryGetValue(TKey key, out TValue value)
{
return _keyValues.TryGetValue(key, out value);
}
public bool Contains(TValue value)
{
return _keyValues.ContainsKey(value.Key);
}
public bool Contains(TKey key)
{
return _keyValues.ContainsKey(key);
}
public bool Remove(TKey key)
{
return _keyValues.Remove(key);
}
public bool Remove(TValue value)
{
return _keyValues.Remove(value.Key);
}
}
public interface IKeyd<TKey> where TKey: IEquatable<TKey>
{
public TKey Key { get; }
}
public class KeyValueCollection<TKey, TValue> where TValue: IKeyd<TKey> where TKey: IEquatable<TKey>
{
private Dictionary<TKey, TValue> _keyValues = new();
public void Add(TValue value)
{
_keyValues.Add(value.Key, value);
}
public bool TryGetValue(TKey key, out TValue value)
{
return _keyValues.TryGetValue(key, out value);
}
public bool Contains(TValue value)
{
return _keyValues.ContainsKey(value.Key);
}
public bool Contains(TKey key)
{
return _keyValues.ContainsKey(key);
}
public bool Remove(TKey key)
{
return _keyValues.Remove(key);
}
public bool Remove(TValue value)
{
return _keyValues.Remove(value.Key);
}
}
6 Replies
mtreit
mtreit9mo ago
I don't see what that adds over just using a dictionary
RumTery
RumTery9mo ago
Dictionaries Contains(TValue value) is O(n), moreover it allows to specify one object for both key and value
Jimmacle
Jimmacle9mo ago
that's why you don't search a dictionary by value, that's not what it's designed to be good at
mtreit
mtreit9mo ago
I mean, in your example it's still looking by key not by value So I don't understand the ask.
Jimmacle
Jimmacle9mo ago
the only real difference here is your collection duplicates the value's key in the value itself
mtreit
mtreit9mo ago
Right, which is just a regular dictionary except there is some limitation requiring the value has a key attached to it. If you want fast lookup by both keys and by values, use two dictionaries. One for regular lookup, one for reverse lookup.