본문 바로가기

프로그래밍/C#

[C#] LINQ 데이터 필터링, 표준 쿼리 연산자

반응형

표준 쿼리 연산자는 LINQ 패턴을 형성하는 메서드입니다.

이를 잘 활용하기 위해 하나하나 정리해보도록 하겠습니다.

순서는 내맘대로. 가장 쉬워보이는거 먼저 정리하겠습니다. 오늘은 데이터 필터링 입니다.

출처는 MSDN 입니다.

 

 

표준 쿼리 연산자 개요 - Visual Basic

표준 쿼리 연산자 개요(Visual Basic)Standard Query Operators Overview (Visual Basic) 이 문서의 내용 --> 표준 쿼리 연산자는 LINQ 패턴을 형성하는 메서드입니다.The standard query operators are the methods that form the LINQ

docs.microsoft.com

 

 


 

필터링 개요

필터링은 지정된 조건을 충족하는 요소만 포함하도록 결과 집합을 제한하는 직업을 가리킴

필터링은 선택이라고도 부름

메서드 종류

- OfType : 지정된 형식의 값들만 선택합니다.

- Where : 조건자 함수를 기반으로 하는 값을 선택합니다.


 

OfType

- 지정된 형식의 값을만 선택하는 메서드입니다.

- 이 메서드는 '지연된 실행' 입니다. ( 코드가 쿼리가 선언되는 지점에서 작업이 수행되지 않고, For Each문 등에서 쿼리 변수가 열거될 경우 실행되는 것을 의미합니다. )

- 이 메서드는 선택되지 않은 값을을 제외시킵니다. 만약 선택되지 않은 값들에서 예외를 검출하려면 'Cast' 메서드를 사용하십시오. // cast는 '데이터 형식 변환' 메서드에 속합니다.

소스코드


System.Collections.ArrayList fruits = new System.Collections.ArrayList(4);
            fruits.Add("Mango");
            fruits.Add("Apple");
            fruits.Add(2.2f);
            fruits.Add(255);
            fruits.Add("Banana");

            // Apply OfType() to the ArrayList.
            IEnumerable<string> query1 = fruits.OfType<string>();
            Console.WriteLine("Elements of type 'string' are:");
            foreach (string fruit in query1)
            {
                Console.WriteLine(fruit);
            }

            Console.WriteLine();

            IEnumerable<float> query2 = fruits.OfType<float>();
            Console.WriteLine("Elements of type 'float' are:");
            foreach (float fruit in query2)
            {
                Console.WriteLine(fruit);
            }

실행결과


Elements of type 'string' are:
Mango
Apple
Banana

Elements of type 'float' are:
2.2

 

 

 

Where

- 지정된 조건을 만족하는 값들만 선택하는 메서드입니다.

- if문처럼 bool값을 기준으로 필터링합니다.

- 이 메서드는 '지연된 실행' 입니다.

소스코드


            // 예제 1
            List<string> fruits =
            new List<string> { "apple", "passionfruit", "banana", "mango",
                    "orange", "blueberry", "grape", "strawberry" };

            IEnumerable<string> query1 = fruits.Where(fruit => fruit.Length < 6);

            Console.WriteLine("Query1:");
            foreach (string fruit in query1)
                Console.WriteLine(fruit);

            // 예제 2
            int[] numbers = { 0, 30, 20, 15, 90, 85, 40, 75 };

            IEnumerable<int> query2 =
                numbers.Where((number, index) => number <= index * 10);

            Console.WriteLine("\nQuery2:");
            foreach (int number in query2)
                Console.WriteLine(number);

 

실행결과


Query1:
apple
mango
grape

Query2:
0
20
15
40

 

 

예제1은 string요소중 길이가 6 이하인 것만 선택하는 코드입니다.

이렇게 Where 메서드는 마치 if문처럼 사용하여 데이터를 쉽게 처리할 수 있습니다.

예제2는 테스트할 요소 옆에 'index'라는 요소가 하나 더 생겼는데,

where문을 사용하는 소스(numbers 배열)의 인덱스 값을 의미합니다.

즉 numbers의 0은 numbers[0]의 값이므로, where 메서드에서 index값은 0이고

30은 numbers[1]의 값이므로 where 메서드에서 index값은 1입니다.

그러므로 '값 0'은 조건식 ( 0 <= 0 * 10 )을 만족해서 query2에 포함되고,

'값 30'은 조건식 ( 30 < = 1 * 10 )에 만족하지 못해서 제외된 결과를 확인할 수 있습니다.

 

 

 

 

 

 

반응형