LINQ

최태선·2022년 3월 14일
0

이것이 C#이다

목록 보기
9/10

1. LINQ란?

데이터 질의 기능이다.
from절에는 IEnumerable< T >를 상속하는 객체만 사용 가능하다. // 배열, 컬렉션 (list,Queue,Stack,Hashable )은 사용가능

var profiles = 
	from profile in arrProfile // arrProfile에서 프로파일들을 추출하여
	where profile.Height < 175 // 키가 175 미만만 골라
    orderby profile.Height; // 키순으로 정렬
    select profile; // profile 객체 추출

2. orderby

orderby profile.Height ascending // 오름차순 정렬
orderby profile.Height descending // 내림차순 정렬

3. select

select 반환형식은 IEnumerable< T > 형식이다.
무명형식도 사용 가능하다.

select profile // IEnumerable<profile> 반환형식
select profile.Name // IEnumerable<string> 반환형식
select new {Name = profile.Name, InchHeight = profile.Height * 0.393} // 무명 형식

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

var classes = 
	from c in arrClass
		from s in c.Score
        where s <60
    select new { c.Name, Lowest = s};

5. group by

group A by B int 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 = g};
    
// True : 김태희 158, 하하172, 고현정 170
// False : 이문세 178, 정우성 184

join

6. 내부조인

내부조인시 두 원본 사이에서 일치하는 데이터끼리 연결시킨다.
데이터가 한곳에만 존재하는 경우 무시된다.

from a in A 
join b in B on a.xxxx equals b.YYYY

var listProfile =
	from profile in arr Profile
    join product in arrProduct on profile.Name equals product.Star
    select new 
    {
    	Name = profile.Name,
        Work = product.Title,
        Height = profile.Height
    };

7. 외부조인

외부조인은 내부조인과 비슷하지만, 기본데이터를 모두 표현한다는 차이가 있다.
C#에서는 왼쪽조인만 지원한다.

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

8. C#쿼리식 문법

C#은 System.Linq에 존재하는 메소드를 쿼리식 문법으로 바꾸는 기능을 제공한다.
Linq에 존재하는 메소드는 55개인데 그중 쿼리를 지원하는 메소드는 11개이다.
쿼리를 지원하지 않는 메소드를 사용하고 싶다면 System.Linq에 존재하는 메소드를 이용하자.

double Average = (
	from profile in arrProfile
	where profile.Height < 180
    select profile).Average(profile=> profile.Height);
profile
최태선입니다

0개의 댓글