119 lines
3.0 KiB
C#
119 lines
3.0 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
namespace ln.types.btree
|
|
{
|
|
public class BTreeValueList<K, V>
|
|
{
|
|
BTree<K, List<V>> bTree;
|
|
|
|
public BTreeValueList()
|
|
{
|
|
bTree = new BTree<K, List<V>>();
|
|
}
|
|
public BTreeValueList(Comparison<K> comparison)
|
|
{
|
|
bTree = new BTree<K, List<V>>(comparison);
|
|
}
|
|
|
|
public IEnumerable<V> this[K key]
|
|
{
|
|
get
|
|
{
|
|
IEnumerable<V> values = null;
|
|
if (TryGet(key,ref values))
|
|
{
|
|
return values;
|
|
}
|
|
throw new KeyNotFoundException();
|
|
}
|
|
}
|
|
|
|
public void Add(K key, V value)
|
|
{
|
|
if (!TryAdd(key, value))
|
|
throw new ArgumentException("duplicate key");
|
|
}
|
|
public void Remove(K key, V value)
|
|
{
|
|
if (!TryRemove(key, value))
|
|
throw new KeyNotFoundException();
|
|
}
|
|
public void Remove(K key)
|
|
{
|
|
if (!TryRemove(key))
|
|
throw new KeyNotFoundException();
|
|
}
|
|
|
|
public bool TryAdd(K key,V value)
|
|
{
|
|
List<V> values = null;
|
|
if (!bTree.TryGet(key,ref values))
|
|
{
|
|
values = new List<V>();
|
|
bTree.Add(key, values);
|
|
}
|
|
values.Add(value);
|
|
return true;
|
|
}
|
|
public bool TryGet(K key,ref IEnumerable<V> values)
|
|
{
|
|
List<V> _values = null;
|
|
if ((!bTree.TryGet(key, ref _values)) || (_values.Count == 0))
|
|
return false;
|
|
|
|
values = _values;
|
|
return true;
|
|
}
|
|
public bool TryRemove(K key)
|
|
{
|
|
return bTree.TryRemove(key);
|
|
}
|
|
public bool TryRemove(K key,V value)
|
|
{
|
|
List<V> values = null;
|
|
if (bTree.TryGet(key, ref values))
|
|
{
|
|
bool success = values.Remove(value);
|
|
if (values.Count == 0)
|
|
bTree.Remove(key);
|
|
return success;
|
|
}
|
|
return false;
|
|
}
|
|
public bool ContainsKey(K key)
|
|
{
|
|
List<V> _values = null;
|
|
if (!bTree.TryGet(key, ref _values))
|
|
return false;
|
|
return _values.Count > 0;
|
|
}
|
|
public bool ContainsValue(V value)
|
|
{
|
|
foreach (List<V> _values in bTree.Values)
|
|
{
|
|
foreach (V v in _values)
|
|
if (v.Equals(value))
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
public int Count(K key)
|
|
{
|
|
List<V> _values = null;
|
|
if ((!bTree.TryGet(key, ref _values)) || (_values.Count == 0))
|
|
return 0;
|
|
return _values.Count;
|
|
}
|
|
|
|
public void Clear()
|
|
{
|
|
bTree.Clear();
|
|
}
|
|
|
|
public IEnumerable<K> Keys => bTree.Keys;
|
|
public IEnumerable<V> Values => bTree.Values.SelectMany(vl => vl);
|
|
}
|
|
}
|