모름

group by

 

링크의 쿼리식에서 group by는 데이터를 그룹으로 분류시켜줍니다. 문법은 아래와 같습니다.

 

group A by B into C

 

A에는 앞서 from에서 뽑아낸 범위변수가 들어가며, B에는 분류 기준(조건)이 들어가고 C에는 그룹 변수가 들어가게 됩니다. 그럼 group by를 사용하는 예제 프로그램을 작성해봅니다.

 

 

 


 

 

 

실습

 

using System;
using System.Linq;

namespace LinqGroupBy
{
    class Profile
    {
        public string Name { get; set; }
        public int    Height { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Profile[] arrProfile =
            {
                new Profile(){Name = "정우성", Height = 186},
                new Profile(){Name = "김태희", Height = 158},
                new Profile(){Name = "고현정", Height = 172},
                new Profile(){Name = "이문세", Height = 178},
                new Profile(){Name = "하하", Height = 171},
            };

            var listProfile = from profile in arrProfile
                              orderby profile.Height
                              group profile by profile.Height < 175 into g
                              select new { GroupKey = g.Key, Profiles = g };

            foreach (var Group in listProfile)
            {
                Console.WriteLine($"- 175 미만 ? : {Group.GroupKey}");

                foreach (var profile in Group.Profiles)
                {
                    Console.WriteLine($"{profile.Name}, {profile.Height}");
                }
            }
        }
    }
}

 

 

 


 

 

 

출력