2015년 3월 9일 월요일

뇌자극 C# 5.0 - 15강

-LINQ-


15.1 데이터!!데이터!!데이터!!


LINQ는 C# 언어에 통합된 데이터 질의 기능이다.
질의란 데이터에 대해 물어본다는 말이다.
기본적인 질문은 다음과 같다

From : 어떤 데이터 집합에서 찾을 것인가?
Where : 어떤 값의 데이터를 찾을 것인가?
Select : 어떤 항목을 추출할 것인가?

List<Profile> profiles = new List<Profile>();
foreach (Profile profile in arrProfile)
{
    if(profile.Height < 175)
         profiles.Add(profile);
}
profiles.Sort(
     (profile1, profile2) =>
     {
        return profile1.Height - profile2.Height;
     }
);
foreach(var profile in profiles)
    Console.WriteLine("{0}, {1}", profile.Name, profile.Height);

위의 코드를 LINQ 로 바꾸면 아래와 같이 된다.

var profiles = from profile in arrProfile //arrProfile 안에 있는 각 데이터로부터
               where profile.Height < 175  //Height가 175 미만인 객체만 골라
               orderby profile.Height   //키순으로 정렬하여
               select profile;             //profile 객체를 추출한다.
foreach (var profile in profiles)
     Console.WriteLine("{0}, {1}", profile.Name, profile.Height);

15.2 LINQ의 기본 : from, where, orderby, select


15.2.1 from

모든 LINQ 쿼리식은 반드시 from 절로 시작한다.
쿼리식의 대상이 될 데이터 원본과 데이터 원본 안에 들어 있는 
각 요소 데이터를 나타내는 범위 변수를 from절에서 지정해 줘야 한다.
이 때 from의 데이터 원본은 아무 형식이나 사용할 수 없고,
IEnumerable<T> 인터페이스를 상속하는 형식이어야 한다.

배열이나 컬렉션 객체들은 IEnumerable<T>를 상속하기 때문에 
이들은 모두 from 절의 데이터 원본으로 사용할수 있다.

from 절을 이용해서 데이터 원본으로 부터 범위 변수를 뽑아낸 후에,
LINQ가 제공하는 수십가지 연산을 이용해서 데이터를 가공 및 추출할 수 있다.

15.2.2 where

where는 필터 역할을 하는 연산자다.
from이 데이터 원본으로부터 뽑아내면 
where 연산자로 조건을 걸어 부합하는 데이터만 걸러낸다.

var profiles = from profile in arrProfile //arrProfile 안에 있는 각 데이터로부터
               where profile.Height < 175  //Height가 175 미만인 객체만 골라
               orderby profile.Height   //키순으로 정렬하여
               select profile;             //profile 객체를 추출한다.

15.2.3 orderby


orderby 는 데이터의 정렬을 수행하는 연산자다.
기본적으로 오름차순으로 데이터를 정렬하지만,
오름차순으로 명시하기 위해서는 ascending 키워드로 명시하면 된다.

var profiles = from profile in arrProfile
               where profile.Height < 175
               orderby profile.Height ascending   //키순 오름차순으로 정렬
               select profile;          

내림차순으로 명시하기 위해서는 descending 키워드로 명시하면 된다

var profiles = from profile in arrProfile
               where profile.Height < 175
               orderby profile.Height  descending //키순 내림차순으로 정렬
               select profile;          

15.2.4 select

select 절은 최종 결과를 추출하는 쿼리식이다.

var profiles = from profile in arrProfile
               where profile.Height < 175
               orderby profile.Height
               select profile.Name;

위와 같이 Name만 추출하면 profiles 에는 string 형식으로 컴파일된다.
또한, select 문은 무명형식을 이용해서 다음과 같이 새로운 형식을 즉성에서 만들수 있다.

var profiles = from profile in arrProfile
               where profile.Height < 175
               orderby profile.Height
               select new {Name=profile, name, InchHeight=profile.Height*0.393};

15.3 여러 개의 데이터 원본에 질의하기


LINQ 쿼리식은 데이터 원본에 접근하기 위해 from절을 사용한다
여러개의 데이터 원본에 접근하려면 from문을 중첩해서 사용하면 된다.

예)

var classes = from c in arrClass    //첫번째 데이터 원본
                  from s in c.Score  //두번째 데이터 원본
                  where s < 60
               select new {c.Name, Lowest = s}; 


15.4 group by 로 데이터 분류하기


데이터를 그룹화 해주는 질의문이다.

group A by B into C

A에는 from 절에서 뽑아낸 범위 변수를, 
B에는 분류 기준을, 
C에는 그룹 변수를 위치 시키면 된다.

예)
var listProfile = from profile in arrProfile
                 group profile by profile.Height < 175 into g
                 select new {GroupKey = g.key, Profiles = 0};

15.5 두 데이터 원본을 연결하는 join


join 은 두 데이터 원본을 연결하는 연산이다.
각 데이터 원본에서 특정 필드의 값을 비교하여 
일치하는 데이터 끼리 연결을 수행한다.

15.5.1 내부조인


내부조인은 교집합과 비슷하다. 
두 데이터 원본 사이에서 일치하는 데이터들만 연결한 후 반환한다.
기준 데이터 a는 from절에서 뽑아낸 범위 변수이고, 
연결 대상 데이터 b는 join 절에서 뽑아낸 변수다. 
join 절의 on 키워드조인 조건을 수반한다
on 절의 조인 조건은 동등만 허용한다.
동등은 == 대신 equals  키워드를 사용한다.

from a in A
join b in B on a.xxx equals b.yyy

15.5.2 외부 조인


외부 조인은 기본적으로 내부 조인과 비슷하지만, 
기준이 되는 데이터 원본은 모두 다 포함된다는 점이 다르다.

예제)

var listProfile = 
   from profile in arrProfile
   join product in arrProduct on profile.Name equals product.Star into ps
   from product in ps.DefaultIfEmpty(new Product(){Title="그런거 없음"})
   select new
   {
      Name = profile.Name,
      Work = product.Title,
      Height = profile.Height
   };

15.6 LINQ의 비밀과 LINQ 표준 연산자


LINQ에는 많은 연산자가 있으나 여기에 다 쓰기엔 너무 힘들다 -_-;
그래서 msdn를 찾아볼 것을 추천한다.

댓글 없음:

댓글 쓰기