有两组数据:
一个是今年的数据
List<PC> current
ID area type total year
----------------------------
1 广州 CPU 10000 2016
2 深圳 显卡 500 2016
一个是去年的数据
List<PC> last
ID area type total year
-------------------------------
1 广州 CPU 20000 2015
2 深圳 显卡 600 2015
3 东莞 SSD 200 2015
统计成这样的今年和去年的对比结果:
area type 2016 2015
--------------------------------
广州 CPU 10000 20000
深圳 显卡 500 600
东莞 SSD - 200
用linq或者c#代码应该怎样实现呢?
using System.Collections.Generic; using System.Linq; namespace ConsoleApplication5 { class Program { static void Main(string[] args) { var lstA1 = new List<A>(); var lstA2 = new List<A>(); var query = from a1 in lstA1 join a2 in lstA2 on new { a1.Area, a1.Type } equals new { a2.Area, a2.Type } select new B { Area = a1.Area, Type = a1.Type, TotalA = a1.Total, TotalB = a2.Total }; var lstB = query.ToList(); } } class A { public string Area { get; set; } public string Type { get; set; } public int Total { get; set; } public int Year { get; set; } } class B { public string Area { get; set; } public string Type { get; set; } /// <summary> /// 2015年total /// </summary> public int TotalA { get; set; } /// <summary> /// 2016年total /// </summary> public int TotalB { get; set; } } }
这个实现只是把两年都有的数据才显示出来。今年有,去年没有的数据该怎么显示出来呢?
@sidecore: 用linq的左连接,由于linq没有右链接(貌似),而且全连接实现比较复杂。
要是有全连接的需求,可以用楼下的方法:先合并两个list->分组->根据条件取值
IEnumerable<pc> all = current.Concat(last); var aresult = from al in all group al by new { al.area, al.type } into ty select new { area = ty.Key.area, type = ty.Key.type, cy = ty.Where(c => c.year == 2016).Sum(c => c.total), ly = ty.Where(c => c.year == 2015).Sum(c => c.total) };