首页 新闻 赞助 找找看

两个集合中的数据,怎样统计到一个比较的集合中?

0
悬赏园豆:5 [待解决问题]

有两组数据:

一个是今年的数据

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#代码应该怎样实现呢?

sidecore的主页 sidecore | 初学一级 | 园豆:2
提问于:2016-01-06 18:18
< >
分享
所有回答(2)
0
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; }
    }
}
Gamain | 园豆:357 (菜鸟二级) | 2016-01-07 11:32

这个实现只是把两年都有的数据才显示出来。今年有,去年没有的数据该怎么显示出来呢?

支持(0) 反对(0) sidecore | 园豆:2 (初学一级) | 2016-01-07 23:30

@sidecore: 用linq的左连接,由于linq没有右链接(貌似),而且全连接实现比较复杂。

要是有全连接的需求,可以用楼下的方法:先合并两个list->分组->根据条件取值

支持(0) 反对(0) Gamain | 园豆:357 (菜鸟二级) | 2016-01-08 11:49
0
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)
                          };
米修君 | 园豆:553 (小虾三级) | 2016-01-07 12:34
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册