合并多个List 中的相同项

public List<int> htidList = new List<int>();//合同id集合
//合同明细 
public IList<Tb_HTMXInfo> htmxList0 = new List<Tb_HTMXInfo>();


Tb_HTMXHelper helper = new Tb_HTMXHelper();
        for (int i = 0; i < htidList.Count; i++)
        {
            //根据合同id查询入库明细
            string sql = string.Format("select * from tableName where hm_author='{0}'", htidList[i].ToString());
            IList<Tb_HTMXInfo> lt = new List<Tb_HTMXInfo>();
            lt = helper.GetAllListBySql(sql);
            //将两个集合合并到第三个容器中
            Dictionary<string, Tb_HTMXInfo> combineResult = new Dictionary<string, Tb_HTMXInfo>();
            foreach (var item in lt.Union(htmxList0))
            {
                //用ContainsKey(编号)方法合并相同的项
                if (!combineResult.ContainsKey(item.Hm_CpXHNumber))
                    combineResult.Add(item.Hm_CpXHNumber, item);
                else
                {
                    //如果存在相同的项,则对数量和金额进行累加
                    combineResult[item.Hm_CpXHNumber].Hm_counts += item.Hm_counts;
                    combineResult[item.Hm_CpXHNumber].Hm_money += item.Hm_money;
                }
            }
            //清空集合
            htmxList0.Clear();
            foreach (var item in combineResult)
            {
                //将合并后的结果集重新复制到第一个集合中,准备跟下一个查询出的集合合并
                htmxList0.Add(item.Value);
            }
        }       
        initHTMXGrid();

 

posted @ 2012-12-12 14:41  玉面麒麟  Views(2132)  Comments(0Edit  收藏  举报