본문 바로가기
프로그래밍/C#

[C#] LINQ group by 사용하기

by 방구석개발자 2020. 4. 9.
반응형

group by로 데이터 분류하기

DB  group by 와 비슷한 역할을 수행합니다.

group by 의 형식

group A by B into C

 

예시 :

using System;
using System.Diagnostics;
using System.Collections;
using System.Linq;

namespace ConsoleApp3
{
    class Student
    {
        public string Name { get; set; }
        public int Score { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Student[] arrStudent =
            {
                new Student(){Name="홍길동",Score=90},
                new Student(){Name="홍이동",Score=80},
                new Student(){Name="김일동",Score=70},
                new Student(){Name="박만수",Score=60},
                new Student(){Name="김천수",Score=50}
            };
            //arrStudent 에  Score 70점 이상 70 미만으로 데이터를 나눠 주세요.

            var arrStudents = from student in arrStudent
                              orderby student.Name ascending
                              group student by student.Score <= 70 into g
                              select new { GroupKey = g.Key, Students = g };
            foreach(var Students in arrStudents)
            {
                Debug.WriteLine(Students.GroupKey);
                foreach(var student in Students.Students){
                    Debug.WriteLine(student.Name + " : " + student.Score);
                }
            }

            

            ExitKey();

        }

        public static void ExitKey()
        {
            Console.WriteLine("계속 하시려면 아무 키나 누르세요.");
            Console.ReadKey();
        }
    }
}

group by 의 해당 결과값

 

반응형

'프로그래밍 > C#' 카테고리의 다른 글

[C#] LINQ 란 무엇인가?  (0) 2020.04.01
[C#] 우아한 프로퍼티 , get set  (0) 2020.03.26
[C#] 공부 정리  (0) 2020.03.22

댓글