본문 바로가기
Programming/C#

C# LINQ GROUP BY

by NAMP 2015. 4. 8.

C# LINQ GROUP BY



Program.cs


Student.cs



using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;


namespace testLinq1

{

    class Student

    {

        public String name {get;set;}

        public int[] score {get;set;}

        public String clazz { get; set; }

        public int qty { get; set; }

    }

}




using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;


namespace testLinq1

{

    class Program

    {

        static void Main(string[] args)

        {

            Program pp = new Program();

            pp.start();

        }


        // 참고 : http://mrw0119.tistory.com/25


        private void start()

        {

            Student[] StudentList = {

                 new Student {name="아라", score= new int[]{88,73,66,91}, clazz="A", qty=1},

                 new Student {name="민희", score= new int[]{78,95,89,52}, clazz="B", qty=2},

                 new Student {name="현아", score= new int[]{88,71,100,91}, clazz="A", qty=3}                                    

            };


            var Students = from student in StudentList

                           from score in student.score

                           where score > 89

                           select new { student.name, score };


            foreach (var student in Students)

                Console.WriteLine("Good: {0} {1}점", student.name, student.score);


           


            var clz = from student in StudentList

                      group student by student.clazz into g

                      select new {clazz = g.Key, sum = g.Sum(_=>_.qty), name = g.Max(_=>_.name)};


            foreach (var s in clz)

                Console.WriteLine("result {0} {1} name:{2}", s.clazz, s.sum, s.name);



            Console.ReadLine();

        }

    }

}



댓글