1. LINQ 란? : ★★★
- LINQ 는 Collection(List, 배열 등)을 SQL 처럼 다룰 수 있는 문법을 말한다.
- Collection 만 사용이 가능한데, 이는 IEnumerable<T> 인터페이스를 Collection이 상속하고 있기 때문임.
예)
1) Query
var result =
from p in products
where p.Price > 100
select p.Name;
2) Method
var result = products
.Where(p => p.Price > 100)
.Select(p => p.Name);
- from(범위) : data 라는 Collection 에서,
- where(조건) : x > 10 인 경우에만,
- select(조회) : x * 2 로 x를 변환하여 > result 에 담는다.
2. Select(조회 및 변환) : ★★★★
1) Query
var result =
from p in products
select p.Name;
2) Method
var result = prodcuts.Select(p => p.Name);
> Product 에서 Name 만 추출
3. Where(조건) : ★★★★
1) Query
var result =
from p in products
where p.Price > 100
select p;
2) Method
var result = products.Where(p => p.Price > 100);
4. OrderBy / OrderByDescending(정렬) : ★★★
1) Query
var result =
from p in products
orderby p.Price descending
select p;
2) Method
var result = products
.OrderByDescending(p => p.Price);
5. GroupBy(그룹) : ★★★
1) Query
var result =
from p in products
group p by p.Category;
2) Method
var result = products
.GroupBy(p => p.Category);
6. Join(연결) : ★★★
1) Query
var result =
from p in products
join c in categories
on p.CategoryId equals c.Id
select new { p.Name, c.CategoryName };
2) Method
var result = products.Join(
categories,
p => p.CategoryId,
c => c.Id,
(p, c) => new { p.Name, c.CategoryName });
7. Group + Select : ★★★
1) Query
var result =
from p in products
group p by p.Category into g
select new
{
Category = g.Key,
Count = g.Count()
};
2) Method
var result = products
.GroupBy(p => p.Category)
.Select(g => new
{
Category = g.Key,
Count = g.Count()
});
8. SelectMany : ★★★★
1) Query(2중 from)
var result =
from t in titles
from word in t.Split(' ')
select word;
2) Method
var result = titles
.SelectMany(t => t.Split(' '));
9. 핵심예제 : ★★★★
1) Query
var result =
from t in titles
from word in t.Split(' ')
group word by word.ToLower() into g
orderby g.Count() descending
select new { Word = g.Key, Count = g.Count() };
2) Method
var result = titles
.SelectMany(t => t.Split(' '))
.GroupBy(w => w.ToLower())
.OrderByDescending(g => g.Count())
.Select(g => new { Word = g.Key, Count = g.Count() });
3) 정리
from → 시작
where → 조건
select → 결과
orderby → 정렬
group by → 그룹
into → 그룹 후 재사용
'C# > Study' 카테고리의 다른 글
| 이것이 C#이다(Chapter 13-2 이벤트) ★★★★★ (0) | 2026.05.01 |
|---|---|
| 이것이 C#이다(Chapter 13-1 대리자) ★★★★★ (0) | 2026.04.06 |
