//============================模拟数据==================================// Dictionary<string, Dictionary<string, object>> dic_dic = new Dictionary<string, Dictionary<string, object>>(); Dictionary<string, object> dic = new Dictionary<string, object>(); dic.Add("name", "回复剂"); dic.Add("type", "药"); dic_dic.Add("0", dic); Dictionary<string, object> dic2 = new Dictionary<string, object>(); dic2.Add("name", "以太"); dic2.Add("type", "药"); dic_dic.Add("1", dic2); Dictionary<string, object> dic3 = new Dictionary<string, object>(); dic3.Add("name", "斧子"); dic3.Add("type", "武器"); dic_dic.Add("2", dic3); //===================================================================// Dictionary<string, List<Dictionary<string, object>>> allDic = new Dictionary<string, List<Dictionary<string, object>>>(); List<Dictionary<string, object>> medList = new List<Dictionary<string, object>>();//药品list List<Dictionary<string, object>> weaList = new List<Dictionary<string, object>>();//武器list for (int i = 0; i < dic_dic.Count; i++) { Dictionary<string, object> d = dic_dic.Values.ElementAt(i); for (int j = 0; j < d.Count; j++) { if (d.Values.ElementAt(j) == "药") { medList.Add(d); } else if (d.Values.ElementAt(j) == "武器") { weaList.Add(d); } } } allDic.Add("药", medList); allDic.Add("武器", weaList);
我想把dic_dic里面的物品数据根据物品的类型进行分类,分类完之后,再把他们存放在一个大字典allDic里面
然后我就这样写了,但是一个问题就是这样写,如果后面数据加了新类型的话,我就要加新的list
能改成后面无论加什么类型的物品,我这边的代码都可以不用动吗?(里面用linq检索就更好了)
class Program
{
static void Main(string[] args)
{
///构造数据
var list = new List<Tools> {
new Tools{ Type="药",Name="回复剂"},
new Tools{ Type="药",Name="以太"},
new Tools{ Type="武器",Name="斧子"}
};
list.Add(new Tools { Type = "衣服", Name = "上衣" });
//根据Type 分组存储
var group = list.GroupBy(x => x.Type);
//获取 Type为药 的集合
var pillList = group.Where(x => x.Key == "药");
}
}
public class Tools
{
/// <summary>
/// 道具类型
/// </summary>
public string Type { get; set; }
/// <summary>
/// 道具名称
/// </summary>
public string Name { get; set; }
}
你可使用HashMap,key就是纯你的类型对应value就存你对应的数据,for循环你的数据判断是否有过这个key(种类)如果没有就添加一个新的,如果有这个keyj就添加到对应位置,
哇,游戏公司的么?什么游戏?什么公司?