Linq(Language-Intergrated Query)는 컬렉션 형태의 데이터(간단하게 리스트)를 쉽게 다루고자, SQL을 본따 만든 구문입니다.
Linq를 사용하면 C# 객체의 집합을 쉽게 관리할 수 있으며, SQL 서버와 함께 연동해서 데이터베이스 관리를 간단하게 할 수도 있습니다.
아래는 데이터를 선별하는 정형화된 코드입니다.
// 입력과 출력을 나타내는 리스트를 생성합니다.
List<int> input = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
List<int> output = new List<int>();
// 입력을 나타내는 리스트에 반복을 적용합니다.
foreach(var item in input)
{
if(item %= 2 == 0)
{
// 출력을 나타내는 리스트에 요소를 추가합니다.
output.Add(item);
}
}
// 출력을 나타내는 배열을 반환합니다.
return output;
이런 코드를 Linq 를 사용해 간단하게 작성할 수 있습니다.
// 입력을 나타내는 리스트를 생성합니다.
List<int> input = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// Linq 질의를 사용해 반환합니다.
return from item in input
where item % 2 == 0
select item;
Linq 구문은 다음과 같이 from, in, where, orderby, select 로 이루어집니다.
// Linq 기본 구문
List<int> input = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var output = from item in input
where item % 2 == 0
orderby itemm
select item;
<from in select 구문>
모든 Linq 질의(쿼리)는 from, in, select 키워드를 포함해야 합니다. 다음과 같이 사용합니다.
from <변수이름> in <컬렉션 이름>
select <결과에 넣을 요소>
이는 다음과 같은 코드라고 할 수 있습니다.
List<int> output = new List<int>();
foreach( var <변수이름> in <컬렉션 이름>)
{
output.Add(<결과에 넣을 요소>);
}
static void Main(string[] args)
{
List<int> input = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var output = from item in input
where item % 2 == 0
orderby item
select item;
foreach(var item in output)
{
Console.WriteLine(item);
}
}
/*
[실행 결과]
1
4
9
16
25
36
49
64
81
100
*/
<where 구문>
where 구문은 조건을 지정할 때 사용합니다.
from <변수 이름> in <컬렉션 이름>
where <조건식>
select <변수 이름>
다음과 같은 코드로 변환이 가능합니다.
List<int> <output> = new List<int>();
foreach(var <변수 이름> in <컬렉션 이름>)
{
if(조건식)
{
output.Add(<결과에 넣을 요소>);
}
}
바로 예제를 살펴보겠습니다.
static void Main(string[] args)
{
List<int> input = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var output = from item in input
where (item > 5) && (item % 2 == 0)
select item;
foreach(var item in output)
{
Console.WriteLine(item);
}
}
/*
[실행 결과]
6
8
10
*/
<orderby 구문>
orderby 구문은 정렬을 해줍니다. 이때 정렬 순서는 ascending(오름차순) 또는 descending(내림차순)을 지정합니다.
아무것도 입력하지 않으면 ascending(오름차순)으로 지정됩니다.
from <변수 이름> in <컬렉션 이름>
where <조건식>
orderby <정렬 대상> <정렬 순서>
select <변수 이름>
마찬가지로 예제를 살펴보겠습니다.
다음 코드는 from in select 구문과 where 구문을 사용해 요소를 선택하고 내림차순으로 정렬한 새로운 리스트를 생성합니다.
static void Main(string[] args)
{
List<int> input = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var output = from item in input
where (item > 5) && (item % 2 == 0)
orderby item descending
select item;
foreach(var item in output)
{
Console.WriteLine(item);
}
}
/*
[실행 결과]
10
8
6
*/
'C# > 프로그래밍 고급' 카테고리의 다른 글
C# 프로그래밍 고급 - 13. Linq 응용 (1) | 2024.05.30 |
---|---|
C# 프로그래밍 고급 - 12. 익명 객체 (0) | 2024.05.30 |
C# 프로그래밍 고급 - 10. 델리게이터와 이벤트 (0) | 2024.05.30 |
C# 프로그래밍 고급 - 09. 델리게이터 응용 (2) | 2024.05.30 |
C# 프로그래밍 고급 - 08. 델리게이터 종류 (1) | 2024.05.30 |