111,129
社区成员
发帖
与我相关
我的任务
分享
//我有以下自定义类型
public class theTypeNameMsg
{
public string theTypeName { set; get; } //姓名
public double KuCun { set; get; } //库存数量
public theTypeNameMsg(string T_theTypeName, double T_KuCun)
{
theTypeName = T_theTypeName;
KuCun = T_KuCun;
}
}
List<theTypeNameMsg> t1 = new List<theTypeNameMsg>() { new theTypeNameMsg("小明", 95), new theTypeNameMsg("张三", 91) };
List<theTypeNameMsg> t2 = new List<theTypeNameMsg>() { new theTypeNameMsg("小明", 80), new theTypeNameMsg("张三", 82), new theTypeNameMsg("李四", 77) };
List<theTypeNameMsg> t3 = ........//合并t1和t2,相同姓名合并一起,且库存相加,t3最终结果只有3个元素,即:("小明", 175) 、("张三", 173)和("李四", 77),请教一个简洁的写法
var query = from x in t1.Concat(t2)
group x by x.theTypeName into g
select new theTypeNameMsg(g.Key, g.Sum(a => a.KuCun));
var t3 = query.ToList();
using System.Linq;
List<theTypeNameMsg> t3 = t1.Union(t2)
.GroupBy(g => g.theTypeName)
.Select(s => new theTypeNameMsg(s.Key, s.Sum(m => m.KuCun)))
.ToList();var t3 = t1.Union(t2).GroupBy(p => p.theTypeName).Select(p => new theTypeNameMsg(p.Key, p.Sum(item => item.KuCun))).ToList();public static void Main(string[] args)
{
//测试数据
List<Student> s1=new List<Student>(){
new Student(){name="1",score=10},
new Student(){name="2",score=20},
new Student(){name="3",score=30},
};
List<Student> s2 = new List<Student>(){
new Student(){name="1",score=10},
new Student(){name="2",score=20},
new Student(){name="3",score=30},
};
//合并
var q = s1.Concat(s2).GroupBy(x=>x.name).Select(x=>new Student{name=x.Key, score=x.Sum(y=>y.score)});
//打印显示
foreach (var item in q)
{
Console.WriteLine(item.name+"----"+item.score);
}
Console.ReadLine();
}
//测试类
public class Student
{
public string name { get; set; }
public int score { get; set; }
}var t3 = t1.Concat(t2).GroupBy(a => a.theTypeName).Select(g => new theTypeNameMsg(g.Key, g.Sum(b => b.KuCun))).ToList();