是否有C#数据结构将键映射到多个值?我有一个项目集合,我想按名称键入; 但是,名称并不是唯一的.Hashtable和Dictionary只允许使用唯一键.查找似乎接近我想要的; 但是,它不是可变的.
是否存在我缺少的内置数据结构,或者我是否需要自己构建一个?
您正在寻找的是多图.
您可能还想查看C5通用集合库,它是免费的并且具有多图的实现.
如果您想要自己动手,一个简单的起点是列表:
Dictionary<TKey,List<TValue>>
Run Code Online (Sandbox Code Playgroud)
但是,你不能以正常的方式添加到这样的字典.您必须首先检查密钥是否已存在,如果是,则获取值(列表)并添加到该密钥.否则,您需要创建列表并使用值填充它.
如果您如此倾向,我建议您考虑使用一组扩展方法来简化添加/删除操作:
public static class MultimapExt
{
public static void Add<TKey,TValue>(
this Dictionary<TKey,List<TValue>> dictionary, TKey key, TValue value )
{
List<TValue> valueList;
if( !dictionary.TryGetValue( key, out valueList )
{
valueList = new List<TValue>();
dictionary.Add( key, valueList );
}
valueList.Add( value );
}
public static void Remove<TKey,TValue>(
this Dictionary<TKey,List<TValue>> dictionary, TKey key, TValue value )
{
List<TValue> valueList;
if( dictionary.TryGetValue( key, out valueList ) )
{
valueList.Remove( value );
if( valueList.Count == 0 )
dictionary.Remove( key );
}
}
}
Run Code Online (Sandbox Code Playgroud)