首页 新闻 会员 周边 捐助

C# List 合并相同元素

0
[已解决问题] 解决于 2016-07-07 17:11

 RT:

复制代码
1  public class model {
2         public string name { get; set; }
3         public int gz { get; set; }
4         public int qian { get; set; }
5     }
6 List<model> list = new List<model>();
7             list.Add(new model { name = "张三", gz = 1000, qian = 2000 });
8             list.Add(new model { name = "李四", gz = 1100, qian = 2500 });
9             list.Add(new model { name = "张三", gz = 600, qian = 1200 });
复制代码

这里根据list中model对象的name字段去合并name值相同的数据,请问应该怎么去做。

想要的结果:

 { name = "李四", gz = 1100, qian = 2500 } 
  { name = "张三", gz = 1600, qian = 3200 } 
Vincent8464的主页 Vincent8464 | 初学一级 | 园豆:17
提问于:2016-07-07 15:08
< >
分享
最佳答案
2

用linq

list.groupby(m=>m.name).select(m=>new{name=m.key,gz=m.sum(a=>a.gz),qian=m.sum(a=>a.qian)})

大概意思就是这样别复制过去然后跟我说不能用.

奖励园豆:5
吴瑞祥 | 高人七级 |园豆:29449 | 2016-07-07 15:12

自己也写了一个:

public class model {
        public string name { get; set; }
        public int gz { get; set; }
        public int qian { get; set; }
    }
List<model> list = new List<model>();
            list.Add(new model { name = "张三", gz = 1000, qian = 2000 });
            list.Add(new model { name = "李四", gz = 1100, qian = 2500 });
            list.Add(new model { name = "张三", gz = 600, qian = 1200 });

list=list.OrderBy(a => a.name);
List<model> ss = new List<model>();
            int gz = 0;
            int qian = 0;
            for (int i = 0; i < list.Count; i++)
            { 
                gz += list[i].gz;
                qian += list[i].qian;

                if (i < list.Count - 1)
                {
                    if (list[i].name != list[i + 1].name)
                    {
                        ss.Add(new model { name = list[i].name, gz = gz, qian = qian }); 
                        gz = 0;
                        qian = 0;
                    }
                }
                else
                { 
                        ss.Add(new model { name = list[i].name, gz = gz, qian = qian });
                        gz = 0;
                        qian = 0; 
                }
            }
Vincent8464 | 园豆:17 (初学一级) | 2016-07-07 17:13
其他回答(4)
0

结果都写错,你叫人怎么回答。

爱编程的大叔 | 园豆:30844 (高人七级) | 2016-07-07 15:30
0

groupby

癫ω倒④ゞ | 园豆:262 (菜鸟二级) | 2016-07-07 15:30
0

。。。

顾晓北 | 园豆:10898 (专家六级) | 2016-07-07 15:31
0

Firen | 园豆:5385 (大侠五级) | 2016-07-07 16:38
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册