C# 键值对,一个键,两个值!
经常使用到Dictionary!但是很多情况,我需要两个值,或者多个值!而且又不想写实体!
于是纠结,很纠结!真心不想写实体!
于是自己写了个!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace HSERP.WMS.Entity.SysCfg
{
/// <summary>
/// 自定义键值对
/// </summary>
/// <typeparam name="B">键</typeparam>
/// <typeparam name="J">值</typeparam>
/// <typeparam name="F">值</typeparam>
[Serializable]
public class SuperDictionary<B, J, F>
{
public int Count = 0;
public List<B> Keys = new List<B>();
public List<MyValue<J, F>> Values = new List<MyValue<J, F>>();
#region 构造方法
public SuperDictionary()
{
}
#endregion
#region 根据键返回值
/// <summary>
/// 查询或添加
/// </summary>
/// <param name="b">键</param>
/// <returns></returns>
public MyValue<J, F> this[B b]
{
get
{
int i = Keys.IndexOf(Keys.First(a => a.Equals(b)));
return Values[i];
}
set
{
MyValue<J, F> mv = value as MyValue<J, F>;
int i = Keys.IndexOf(Keys.First(a => a.Equals(b)));
Values[i] = mv;
}
}
#endregion
#region 添加值
/// <summary>
/// 添加
/// </summary>
/// <param name="b">键</param>
/// <param name="j">值</param>
/// <param name="f">值</param>
public void Add(B b, J j, F f)
{
Keys.Add(b);
MyValue<J, F> mv = new MyValue<J, F>();
mv.MyJ = j;
mv.MyF = f;
Values.Add(mv);
Count++;
}
#endregion
#region 删除
public void Remove(B b)
{
int i = Keys.IndexOf(Keys.First(a => a.Equals(b)));
Values.RemoveAt(i);
}
#endregion
}
[Serializable]
public class MyValue<J,F>
{
private J _MyJ;
public J MyJ
{
get { return _MyJ; }
set { _MyJ = value; }
}
private F _MyF;
public F MyF
{
get { return _MyF; }
set { _MyF = value; }
}
}
}
Dictionary<int, Tuple<string, int>> vals = new Dictionary<int, Tuple<string, int>>();
vals.Add(1,new Tuple<string,int>("hello",1));