C#/기초

[C#] LINQ

딸기우유중독 2022. 2. 21. 15:50

Group By

using System;
using System.Linq;

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

    class MainApp
    {
        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 };	// g.key = true or false

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

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

Join

using System;
using System.Linq;

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

    class Product
    {
        public string Title { get; set; }
        public string Star { get; set; }
    }

    class MainApp
    {
        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}                
            };

            Product[] arrProduct = 
            {
                new Product(){Title="비트",        Star="정우성"},
                new Product(){Title="CF 다수",     Star="김태희"},
                new Product(){Title="아이리스",    Star="김태희"},
                new Product(){Title="모래시계",    Star="고현정"},
                new Product(){Title="Solo 예찬",   Star="이문세"}
            };
			//내부 조인
            var listProfile = 
                from profile in arrProfile
                join product in arrProduct on profile.Name equals product.Star
                select new 
                { 
                    Name = profile.Name, 
                    Work = product.Title,
                    Height = profile.Height
                };

            Console.WriteLine("--- 내부 조인 결과 ---");
            foreach (var profile in listProfile)
            {
                Console.WriteLine("이름:{0}, 작품:{1}, 키:{2}cm", 
                    profile.Name, profile.Work, profile.Height);
            }
			//외부 조인
            listProfile = 
                from profile in arrProfile
                join product in arrProduct on profile.Name equals product.Star into ps
                from sub_product in ps.DefaultIfEmpty(new Product(){Title="그런거 없음"})
                select new
                {
                    Name = profile.Name,
                    Work = sub_product.Title,
                    Height = profile.Height
                };

            Console.WriteLine();
            Console.WriteLine("--- 외부 조인 결과 ---");
            foreach (var profile in listProfile)
            {
                Console.WriteLine("이름:{0}, 작품:{1}, 키:{2}cm",
                    profile.Name, profile.Work, profile.Height);
            }
        }
    }
}

LINQ 연산 메소드 사용

using System;
using System.Linq;

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

    class MainApp
    {
        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 heightStat = from profile in arrProfile
                           group profile by profile.Height < 175 into  g
                           select new
                           {
                               Group   = g.Key==true?"175미만":"175이상",
                               Count   = g.Count(),
                               Max     = g.Max(profile => profile.Height),
                               Min     = g.Min(profile => profile.Height),
                               Average = g.Average(profile => profile.Height)
                           };
			// heightStat 그룹으로 나뉘어진 변수
            foreach (var stat in heightStat)
            {
                Console.Write("{0} - Count:{1}, Max:{2}, ",
                    stat.Group, stat.Count, stat.Max);
                Console.WriteLine("Min:{0}, Average:{1}",
                    stat.Min, stat.Average);
            }
        }
    }
}

 


아래 예제는 같은 결과.

아이템 x를 x.Id로 그룹핑한 후 각 그룹 아이템 y의 마지막 아이템을 select

 

 

 


출처: 이것이 C#이다.

728x90