
LINQ에서 쿼리 변수는 쿼리의 결과 대신 쿼리를 저장하는 변수.
쿼리 변수는 항상 foreach문이나 IEnumerator.MoveNext 메서드에 대한 직접 호출에서 반복될 때 요소 시퀀스를 생성하는 Enumerable 형식
int[] scores = { 90, 71, 82, 93, 75, 82 };
IEnumerable<int> scoreQuery = from score in scores
where score > 80
orderby score descending
select score;
foreach(int testScore in scoreQuery)
{
Console.WriteLine(testScore);
}
쿼리 변수 저장 방법 2가지
IEnumerable<City> queryMajorCities = from city in cities
where city.Population > 100000
select city;
IEnumerable<City> queryMajorCities2 = cities.Where(c => c.Population > 100000);
int[] scores = { 90, 71, 82, 93, 75, 82 };
int hightestScore = (from score in scores
select score).Max();
IEnumerable<int> scoreQuery = from score in scores
select score;
int hightScore = scoreQuery.Max();
int hightScore = scores.Max();
List<City> largeCitiesList = (from country in countires
from city in country.Cities
where city.Population > 10000
select city).ToList();
IEnumerable<City> largeCitiesQuery = from country in countries
from city in country.Cities
where city.Population > 10000
select city;
List<CIty> largeCitiesList2 = largeCities.Query.ToList();
쿼리 변수의 명시적 형식 및 암시적 형식
일반적으로 쿼리 변수와 select 절 간의 형식 관계를 표시하기 위해 쿼리 변수의 명시적 형식을 제공
그러나 var 키워드를 사용하여 컴파일 시간에 쿼리 변수(또는 다른 지역 변수)의 형식을 추론하도록 컴파일러에 지시할 수도 있음.
var queryCities = from city in cities
where city.Population > 100000
select city;
쿼리 식 시작
쿼리 식은 from 절로 시작해야함
쿼리 식은 범위 변수와 함께 데이터 소스를 지정한다.
범위 변수는 소스 시퀀스가 트래버스할 때 소스 시퀀스의 각 연속 요소를 나타낸다.
범위 변수는 데이터 소스의 요소 형식을 기반으로 강력하게 형식지 지정된다.
IEnumerable<Country> countryAreQuery = from country in countries
where country.Area > 500000
select country;
쿼리가 세미콜론 또는 continuation 절로 종료될 때까지 범위 변수는 범위 내에 있음
쿼리 식에는 여러 from 절이 포함될 수 있음.
소스 시퀀스의 각 요소가 컬렉션이거나 컬렉션을 포함하는 경우 from 절을 추가로 사용해야합니다.
ex ) Country 개체의 컬렉션이 있으며, 각각에 Cities라는 이름이 City 개체 컬렉션이 포함되어 있다고 가정
각 Country에서 City 개체를 쿼리하려면 다음과 같이 두 개의 from 절을 사용합니다.
IEnumberable<City> cityQuery = from country in coutries
from city in country.Cities
where city.Population > 10000
select city;
쿼리 식 종료
쿼리 식은 group 절 또는 select 절로 끝나야 합니다.
group 절
지정한 키로 구성되는 그룹의 시퀀스를 생성하려면 group 절을 사용
키의 데이터 형식은 무억이든 가능
` 다음 쿼리는 하나 이상의 Country 개체를 포함하며 키가 char 값인 그룹의 시퀀스를 만든다
var queryCountryGroups = from country in countries
group country by country.Name[0];
select 절
다른 모든 시퀀스 형식을 생성하려면 select 절을 사용한다.
간단한 select 절은 데이터 소스에 포함된 개체와 동일한 개체 형식의 시퀀스를 생성
`- 이 예제에서는 데이터 소스에 Country 개체가 포함된다. orderby 절은 단지 요소를 새로운 순서로 정렬하고, select 절은 다시 정렬된 Country 개체의 시퀀스를 생성한다.
IEnumberable<Country> soretedQuery = from country in countries orderby country.Area
orderby country.Area
select country;
'Language > C#' 카테고리의 다른 글
| Dictionary 연습 (0) | 2020.02.12 |
|---|---|
| [C#] 문자열 엔터처리하기 (0) | 2020.02.12 |
| [c#]treelistview 노드코드 (0) | 2020.02.03 |
| [C#] Datagridview 마지막 빈 행 지우기 (1) | 2020.01.31 |
| [C#] 검색 기능 구현 - 입력하자마자 검색 (0) | 2020.01.30 |