大概查了一下C#的集合貌似没有能双向查询的键值对,项目开发中经常用到双向查询,比如通过数据库字段名查EM实体模型属性或字段名,通过EM实体模型属性字段名查询对应的数据库名。刚好学习一下自定义泛型,搞个KeyValue泛型类,实现双向查询。
1KeyValue类图设计
其实自定义泛型也很简单,KeyValue用2个1对1的List泛型集合即可实现。类的设计图如下:
2KeyValue代码
using System;
using System.Collections.Generic;
using System.Linq;
namespace KeyValue
{
/// <summary>
/// 定义泛型KeyValue,可以双向查询,200218 made by BLMa
/// </summary>
/// <typeparam name="TKey"></typeparam>
/// <typeparam name="TValue"></typeparam>
public class KeyValue<TKey, TValue>
{
/// <summary>
/// Keys键表
/// </summary>
public List<TKey> tKey = new List<TKey>();
/// <summary>
/// Values值表
/// </summary>
public List<TValue> tValue = new List<TValue>();
/// <summary>
/// 集合数
/// </summary>
public int Count { get { return tKey.Count; } }
/// <summary>
/// Add 方法,增加一对键值
/// </summary>
/// <param name="tkey"></param>
/// <param name="tvalue"></param>
public void Add(TKey tkey,TValue tvalue)
{
if (tKey.Contains<TKey>(tkey) || tValue.Contains<TValue>(tvalue) )
throw new ArgumentException("tKey 或 tValue重复");
tKey.Add(tkey);
tValue.Add(tvalue);
}
/// <summary>
/// 按Key键查询Value值
/// </summary>
/// <param name="tkey"></param>
/// <returns></returns>
public TValue Key2Value(TKey tkey)
{
int ik = tKey.BinarySearch(tkey);
if (ik < 0)
throw new ArgumentException("tKey 没找到");
return tValue[ik];
}
/// <summary>
/// 按Value值查询Key键
/// </summary>
/// <param name="tvalue"></param>
/// <returns></returns>
public TKey Value2Key(TValue tvalue)
{
int iv = tValue.BinarySearch(tvalue);
if ( iv < 0)
throw new ArgumentException("tValue 没找到");
return tKey[iv];
}
/// <summary>
/// 清空
/// </summary>
public void Clear()
{
tKey.Clear();
tValue.Clear();
}
/// <summary>
/// 按Key键删除
/// </summary>
/// <param name="tkey"></param>
/// <returns></returns>
public bool RemoveByKey(TKey tkey)
{
int ik = tKey.BinarySearch(tkey);
if (ik < 0)
throw new ArgumentException("tKey 没找到");
tKey.Remove(tkey);
tValue.RemoveAt(ik);
return true;
}
/// <summary>
/// 按Value值删除
/// </summary>
/// <param name="tkey"></param>
/// <returns></returns>
public bool RemoveByValue(TValue tvalue)
{
int iv = tValue.BinarySearch(tvalue);
if (iv < 0)
throw new ArgumentException("tValue 没找到");
tValue.Remove(tvalue);
tKey.RemoveAt(iv);
return true;
}
}
}
3KeyValue应用示例
直接上示例代码,一看就明白
//声明KeyValue键值
KeyValue<string, string> kv = new KeyValue<string, string>();
//增加键值对
kv.Add("1", "A");
kv.Add("2", "B");
kv.Add("3", "C");
kv.Add("4", "D");
kv.Add("5", "E");
//键值对数
int ic = kv.Count;
Count = 5
//键查值
string value = kv.Key2Value("3");
value = C
//值查键
string key = kv.Value2Key("D");
key = 4
//通过Key键删除
bool br = kv.RemoveByKey("4");
br = True Count = 4
//通过Value值删除
bool bv = kv.RemoveByValue("C");
bv = True Count = 3
//清空
kv.Clear();
Count = 0