상세 컨텐츠

본문 제목

LINQ

Programming/C#

by 양명 2019. 2. 13. 09:19

본문

소스코드 업로드 사이트(https://colorscripter.com/)


1. LINQ란? 

Language-INtegrated Query

기본 코딩 패턴으로 쿼리문을 처리할 수 있음


LINQ 작업은 아래 3가지 작업으로 구성됨

1) 데이터 소스 가져오기.

2) 쿼리 만들기.

3) 쿼리 실행.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LINQ
{
class Program
{
//Language-INtegrated Query
static void Main(string[] args)
{
//1) 데이터 소스
int[] numbers = new int[7] { 0, 1, 2, 3, 4, 5, 6 };
//2) 쿼리 생성(일반 sql문과 반대)
//제네릭 IEnumerable<T> 인터페이스를 암시적으로 지원
//지정된 형식의 컬렉션을 단순 반복할 수 있도록 지원하는 열거자(Enumerator)를 노출함.
//IEnumerable<int> numQuery = from num in numbers where (num % 2) == 0 select num;
var numQuery = from num in numbers where (num % 2) == 0 select num; //var 키워드 사용해서 컴파일러가 변수 형식 알아서 체크하도록 할 수 있음
//3) 쿼리 실행
foreach (int num in numQuery)
{
Console.Write("{0,2}", num);
}
}
}
}


2. 데이터를 결합하여 단일 시퀀스로 출력 가능
var peopleInSeattle = (from student in students
where student.City == "Seattle"
select student.Last)
.Concat(from teacher in teachers
where teacher.City == "Seattle"
select teacher.Last);


3. XML form으로 출력하기
public class XMLTransform
{
public void TransformXML()
{
// Create the data source by using a collection initializer.
// The Student class was defined previously in this topic.
List<Student> students = new List<Student>()
{
new Student {First="Svetlana", Last="Omelchenko", ID=111, Scores = new List<int>{97, 92, 81, 60}},
new Student {First="Claire", Last="O’Donnell", ID=112, Scores = new List<int>{75, 84, 91, 39}},
new Student {First="Sven", Last="Mortensen", ID=113, Scores = new List<int>{88, 94, 65, 91}},
};
// Create the query.
var studentsToXML = new XElement("Root",
new XAttribute("Type", "RootAttribute"), // XAttribute로 태그 속성 정의 가능
from student in students
let scores = string.Join(",", student.Scores) //score 리스트를 문자열로 합쳐주는 구문?
select new XElement("student",
new XElement("First", student.First),
new XElement("Last", student.Last),
new XElement("Scores", scores)
) // end "student"
); // end "Root"
/* OUTPUT
* <Root Type="RootAttribute">
<student>
<First>Svetlana</First>
<Last>Omelchenko</Last>
<Scores>97,92,81,60</Scores>
</student>
<student>
<First>Claire</First>
<Last>O’Donnell</Last>
<Scores>75,84,91,39</Scores>
</student>
<student>
<First>Sven</First>
<Last>Mortensen</Last>
<Scores>88,94,65,91</Scores>
</student>
</Root>
*/
// Execute the query.
Console.WriteLine(studentsToXML);
// Keep the console open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}

4. 쿼리에서 연산하기
public class FormatQuery
{
public void ExecuteFormatQuery()
{
// Data source.
double[] radii = { 1, 2, 3 };
// Query.
IEnumerable<string> query =
from rad in radii
select $"Area = {rad * rad * Math.PI:F2}"; //$키워드를 앞에 붙여서 "{}"; 안에 연산 식을 작성. F2는 소수점 2째자리까지 표기
// Query execution.
foreach (string s in query)
Console.WriteLine(s);
// Keep the console open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}


5. 메소드 기반 쿼리 작성(람다 표현)
public class MethodSyntax
{
public void ExecuteMethodSyntax()
{
int[] numbers = { 5, 10, 8, 3, 6, 12 };
//Query syntax:
IEnumerable<int> numQuery1 =
from num in numbers
where num % 2 == 0
orderby num
select num;
//Method syntax:
var numQuery2 = numbers.Where(num => num % 2 == 0).OrderBy(n => n); //람다
foreach (int i in numQuery1)
{
Console.Write(i + " ");
}
Console.WriteLine(System.Environment.NewLine);
foreach (int i in numQuery2)
{
Console.Write(i + " ");
}
// Keep the console open in debug mode.
Console.WriteLine(System.Environment.NewLine);
Console.WriteLine("Press any key to exit");
Console.ReadKey();
}
}


'Programming > C#' 카테고리의 다른 글

Dispose  (0) 2019.02.14
미리 정의된 형식 'System.ValueTuple`2'을(를) 정의하지 않았거나 가져오지 않았습니다.  (0) 2019.02.13
Lambda Expression  (0) 2019.02.12
EventHandler  (0) 2019.02.12
Delegate  (0) 2019.01.29

관련글 더보기