Dictionary.TryGetValue(key,out object)的应用
以前在项目中,经常会遇到从数据库中读取数据,然后通过相同的key去组装Dictionary<key,List<objetct>>这种数据库结构的对象。
最开始的处理方法,一直都是定义一个临时对象,然后把数据库中的对象与之相比较,是同一个key就添加到list对象中,如果不是,就重新构建一个list,然后将之前的list添加到Dictionary中。
这种写法虽然简单,但是经常会忘记将最后一组list添加到Dictionary中,因为需要在循环的外面再次一次添加操作。
后来听组里的同事说到Dictionary.TryGetValue()这个方法更加方便,于是就研究了一下,再次mark一下。
最终的对象:
Dictionary<string, Dictionary<SubjectStages, FileGeneration>> fileGenerationDictionary = new Dictionary<string, Dictionary<SubjectStages, FileGeneration>>();
临时对象:
Dictionary<SubjectStages, FileGeneration> tempFileGenerationDictionary = null;
循环操作:
using (IDataReader idr = Db.ExecuteReader(cmd))
{
while (idr.Read())
{
#region 构建对象
FileGeneration fileGeneration = new FileGeneration();
fileGeneration.OrgCode = idr["orgCode"].ToString();
fileGeneration.OrgName = idr["orgName"].ToString();
#endregion
if (fileGenerationDictionary.TryGetValue(fileGeneration.OrgCode, out tempFileGenerationDictionary))
{
tempFileGenerationDictionary.Add(fileGeneration.SubjectStages, fileGeneration);
fileGenerationDictionary[fileGeneration.OrgCode] = tempFileGenerationDictionary;
}
else
{
tempFileGenerationDictionary = new Dictionary<SubjectStages, FileGeneration>();
tempFileGenerationDictionary.Add(fileGeneration.SubjectStages, fileGeneration);
fileGenerationDictionary.Add(fileGeneration.OrgCode, tempFileGenerationDictionary);
}
}
}

浙公网安备 33010602011771号