Linq行列轉換

  • 72
  • 0

筆記一下

class Program
    {
        static void Main(string[] args)
        {
            List<A> aList = new List<A>
            {
                new A {years = 2017,season="Q1",money=200},
                new A {years = 2017,season="Q2",money=250},
                new A {years = 2017,season="Q3",money=235},
                new A {years = 2017,season="Q4",money=266},
                new A {years = 2018,season="Q1",money=195},
                new A {years = 2018,season="Q2",money=220},
                new A {years = 2018,season="Q3",money=215},
                new A {years = 2018,season="Q4", money=240}
            };

            foreach(var item in aList)
            {
                Console.WriteLine($"{item.years}\t{item.season}\t{item.money}");
            }
            Console.WriteLine();


            var bList = aList.GroupBy(g => g.years)
                .Select(g => new
                {
                    年度 = g.Key,
                    Q1 = g.Where(w => w.season == "Q1").Sum(s => s.money),
                    Q2 = g.Where(w => w.season == "Q2").Sum(s => s.money),
                    Q3 = g.Where(w => w.season == "Q3").Sum(s => s.money),
                    Q4 = g.Where(w => w.season == "Q4").Sum(s => s.money)
                });

            Console.WriteLine("年度\tQ1\tQ2\tQ3\tQ4");
            Console.WriteLine(new string('-',40));
            foreach(var item in bList)
            {
                Console.WriteLine($"{item.年度}\t{item.Q1}\t{item.Q2}\t{item.Q3}\t{item.Q4}");
            }

            Console.ReadKey();
        }
    }


    class A
    {
        public int years { get; set; }
        public string season { get; set; }
        public int money { get; set; }
    }