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 }
用linq
list.groupby(m=>m.name).select(m=>new{name=m.key,gz=m.sum(a=>a.gz),qian=m.sum(a=>a.qian)})
大概意思就是这样别复制过去然后跟我说不能用.
自己也写了一个:
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; } }
结果都写错,你叫人怎么回答。
groupby
。。。