관리 메뉴

샐님은 개발중

1. GROUP BY (단일,여러개) 본문

LINQ

1. GROUP BY (단일,여러개)

샐님 2024. 2. 20. 13:08
728x90
반응형

 

using System;
using System.Linq;



class Program
{
    static void Main(string[] args)
    {
        List<Customer> list = new List<Customer>(); 
        list.Add(new Customer() { Id = 1, Name = "홍길동", Country = "한국", Age = 22 });
        list.Add(new Customer() { Id = 2, Name="이순신", Country="한국", Age = 21});
        list.Add(new Customer() { Id = 3, Name="김갑동", Country="한국", Age = 22});
        list.Add(new Customer() { Id = 4, Name="차우림", Country="미국", Age = 24});
        list.Add(new Customer() { Id = 5, Name="고길동", Country="중국", Age = 22});
        list.Add(new Customer() { Id = 5, Name="제시", Country="미국", Age = 22});
        list.Add(new Customer() { Id = 5, Name="미카", Country="일본", Age = 21});
        list.Add(new Customer() { Id = 5, Name="미사", Country="일본", Age = 21});

        // 나라별 group by
        var result =
              from c in list
              group c by c.Country;
        var result2 =
             list.GroupBy(c => c.Country);
        foreach(IGrouping<string, Customer> group in result)
        {
            Console.WriteLine(group.Key + ":");
            foreach (Customer c in group)
                Console.WriteLine(" " + c.Name);
        }

        Console.WriteLine("group by 여러개");
        //Country 와 Age 로 group by  및 Count(), Sum(), Average() 를 사용해서 집계할 수 있다.
        var result3 =
              list.GroupBy(x => new
              {
                  x.Country,
                  x.Age
              })
              .Select(x => new CustomerGroup
              {
                  Country = x.Key.Country,
                  Age = x.Key.Age,
                  Sum = x.Count()
              });

        foreach(var i in result3 ) {
            Console.WriteLine(i.Country +  i.Age + " " + i.Sum +" 명 입니다.");
        }
        
    }

   

    public class Customer
    {
        public int Id { get; set; }   
        public string? Name { get; set; }   
        public int Age { get; set; }   
        public string? Country { get; set; }   
        public string? NicName { get; set; }   
    }

    public class CustomerGroup
    {
        public int Sum { get; set; }
        public string? Country { get; set; }
        public int Age { get; set; }
       
    }
}

 

728x90
반응형

'LINQ' 카테고리의 다른 글

PIVOT :Transform data from rows to column  (0) 2024.04.08
LINQ 에서 String 문자열을 DateTime 형식과 비교  (0) 2024.04.02
2. Join  (0) 2024.02.20