LINQ의 개요

Similar documents
C# Programming Guide - Types

초보자를 위한 C# 21일 완성

윈도우시스템프로그래밍

untitled

4. #include <stdio.h> #include <stdlib.h> int main() { functiona(); } void functiona() { printf("hihi\n"); } warning: conflicting types for functiona

Microsoft PowerPoint - CSharp-10-예외처리

untitled

Microsoft PowerPoint - 27.pptx

Linq and XML for Microsoft Visual Basic Developer

쉽게 풀어쓴 C 프로그래밊

DBMS & SQL Server Installation Database Laboratory

Mobile Service > IAP > Android SDK [ ] IAP SDK TOAST SDK. IAP SDK. Android Studio IDE Android SDK Version (API Level 10). Name Reference V

chap10.PDF

PowerPoint 프레젠테이션

@OneToOne(cascade = = "addr_id") private Addr addr; public Emp(String ename, Addr addr) { this.ename = ename; this.a

C++ Programming

RDB개요.ppt

목차 BUG 문법에맞지않는질의문수행시, 에러메시지에질의문의일부만보여주는문제를수정합니다... 3 BUG ROUND, TRUNC 함수에서 DATE 포맷 IW 를추가지원합니다... 5 BUG ROLLUP/CUBE 절을포함하는질의는 SUBQUE


MS-SQL SERVER 대비 기능

ALTIBASE 사용자가이드 Templete

Modern Javascript

PowerPoint Presentation

슬라이드 1

ThisJava ..

ilist.add(new Integer(1))과 같이 사용하지 않고 ilist.add(1)과 같이 사용한 것은 자바 5.0에 추가된 기본 자료형과 해당 객체 자료 형과의 오토박싱/언박싱 기능을 사용한 것으로 오토박싱이란 자바 컴파일러가 객체를 요구하는 곳에 기본 자료형

13주-14주proc.PDF

Connection 8 22 UniSQLConnection / / 9 3 UniSQL OID SET

윈도우시스템프로그래밍

1

쉽게 풀어쓴 C 프로그래밍

10.ppt

untitled

Eclipse 와 Firefox 를이용한 Javascript 개발 발표자 : 문경대 11 년 10 월 26 일수요일

thesis

8 장데이터베이스 8.1 기본개념 - 데이터베이스 : 데이터를조직적으로구조화한집합 (cf. 엑셀파일 ) - 테이블 : 데이터의기록형식 (cf. 엑셀시트의첫줄 ) - 필드 : 같은종류의데이터 (cf. 엑셀시트의각칸 ) - 레코드 : 데이터내용 (cf. 엑셀시트의한줄 )

PHPoC vs PHP > 개요 개요 PHPoC 는솔내시스템 이자체개발한프로그래밍언어입니다. 당사의모든 PHPoC 제품들의펌웨어에는 PHPoC 인터프리터가내장되어있습니다. PHPoC 는범용스크립트언어인 PHP 를기반으로제작되었습니다. PHPoC 는매우간단하여 C 언어등

Spring Boot/JDBC JdbcTemplate/CRUD 예제

API - Notification 메크로를통하여어느특정상황이되었을때 SolidWorks 및보낸경로를통하여알림메시지를보낼수있습니다. 이번기술자료에서는메크로에서이벤트처리기를통하여진행할예정이며, 메크로에서작업을수행하는데유용할것입니다. 알림이벤트핸들러는응용프로그램구현하는데있어

구축환경 OS : Windows 7 그외 OS 의경우교재 p26-40 참조 Windows 의다른버전은조금다르게나타날수있음 Browser : Google Chrome 다른브라우저를사용해도별차이없으나추후수업의모든과정은크롬사용 한

Microsoft PowerPoint - hci2-lecture12 [호환 모드]

유니티 변수-함수.key

JAVA PROGRAMMING 실습 02. 표준 입출력

슬라이드 1

예제 2) Test.java class A intvar= 10; void method() class B extends A intvar= 20; 1"); void method() 2"); void method1() public class Test 3"); args) A

Interstage5 SOAP서비스 설정 가이드

Microsoft PowerPoint - C++ 5 .pptx

Microsoft PowerPoint Predicates and Quantifiers.ppt

Microsoft PowerPoint - Chapter 6.ppt

Ç¥Áö

TITLE

3 S Q L A n t i p a t t e r n s Trees/intro/parent.sql CREATE TABLE Comments ( comment_id SERIAL PRIMARY KEY, parent_id BIGINT UNSIGNED, comment TEXT

2파트-07

PowerPoint 프레젠테이션

歯엑셀모델링

슬라이드 1

Microsoft PowerPoint - 8ÀÏ°_Æ÷ÀÎÅÍ.ppt

DataBinding

untitled

07 자바의 다양한 클래스.key

슬라이드 1

Introduction to Geotechnical Engineering II

강의 개요

Microsoft PowerPoint - ch09 - 연결형리스트, Stack, Queue와 응용 pm0100

rmi_박준용_final.PDF

ALTIBASE HDB Patch Notes

example code are examined in this stage The low pressure pressurizer reactor trip module of the Plant Protection System was programmed as subject for

슬라이드 1

Data Sync Manager(DSM) Example Guide Data Sync Manager (DSM) Example Guide DSM Copyright 2003 Ari System, Inc. All Rights reserved. Data Sync Manager

SIGPLwinterschool2012

교육2 ? 그림

PowerPoint Presentation

The Self-Managing Database : Automatic Health Monitoring and Alerting

(Humphery Kim) RAD Studio : h=p://tech.devgear.co.kr/ : h=p://blog.hjf.pe.kr/ Facebook : h=p://d.com/hjfactory :

PowerPoint 프레젠테이션

MPLAB C18 C

PowerPoint Template

PowerPoint Presentation

Analytics > Log & Crash Search > Unity ios SDK [Deprecated] Log & Crash Unity ios SDK. TOAST SDK. Log & Crash Unity SDK Log & Crash Search. Log & Cras

3ÆÄÆ®-11

3ÆÄÆ®-14

목차 BUG DEQUEUE 의 WAIT TIME 이 1 초미만인경우, 설정한시간만큼대기하지않는문제가있습니다... 3 BUG [qp-select-pvo] group by 표현식에있는컬럼을참조하는집합연산이존재하지않으면결괏값오류가발생할수있습니다... 4

<FEFF E002D B E E FC816B CBDFC1B558B202E6559E830EB C28D9>

Microsoft PowerPoint 자바-기본문법(Ch2).pptx

chap 5: Trees

MySQL-.. 1

PowerPoint Presentation

Microsoft PowerPoint 세션.ppt

JAVA PROGRAMMING 실습 05. 객체의 활용

FileMaker ODBC and JDBC Guide

PowerPoint 프레젠테이션

11강-힙정렬.ppt

<4D F736F F F696E74202D20C1A63038C0E520C5ACB7A1BDBABFCD20B0B4C3BC4928B0ADC0C729205BC8A3C8AF20B8F0B5E55D>

DocsPin_Korean.pages

(Microsoft PowerPoint - hci2-lecture12 [\310\243\310\257 \270\360\265\345])

05-class.key

어댑터뷰

MySQL-Ch10

강의10

untitled

Transcription:

LINQ 의개요 이수겸 @ 올랩컨설팅 K E N I A L L E E _ A T _ G M A I L. C O M H T T P : / / K E N I A L. T I S T O R Y. C O M 2 0 0 7. 1 0. 6

LINQ.NET Language-INtegrated Query.NET 프레임워크 3.5, Visual Studio 2 008(Orcas) 적용 관계형데이터베이스나 XML 기반의데이터를다루는기능을프로그래밍언어나런타임에추가하는대신에, 모든정보의소스에접근할수있는범용의조회기능을.NET 프레임워크에추가하는프로젝트 일종의언어확장 (Language-Extensio n) 이며, XML(LINQ to XML), 데이터베이스 (LINQ to SQL, LINQ to Datase t 및 LINQ to Entities 를포함하는 LIN Q 지원 ADO.NET), 개체 (LINQ to Obj ects) 등의타입을다룸

표준쿼리연산자 Standard Query Operators Array의경우 : static void Main() { string[] names = { "Burke", "Connor", "Frank", "Everett", "Albert", "George", "Harris", "David" }; IEnumerable<string> query = from s in names where s.length == 5 orderby s select s.toupper(); foreach (string item in query) Console.WriteLine(item); query 변수는쿼리표현식 (query expression) 으로초기화된다. where, orderby, select 가나타나는것을볼수있다.

표준쿼리연산자 (cont.) VB 코드 : 언어가다름에도기본적으로별차이가없다. Dim query As IEnumerable(Of String) = From s in names _ Where s.length = 5 _ Order By s _ Select s.toupper() 람다식을사용한경우 : IEnumerable<string> query = names.where(s => s.length == 5).OrderBy(s => s).select(s => s.toupper());

람다식 (Lambda Expressions) 기본적으로 C# 2.0 의 delegate 를이용한익명메서드와비슷한성격 만약 C# 2.0 의 deleg ate, 익명메서드를사용해서구현한다면 : Func<string, bool> filter = s => s.length == 5; Func<string, string> extract = s => s; Func<string, string> project = s => s.toupper(); IEnumerable<string> query = names.where(filter).orderby(extract).select(project); Func<string, bool> filter = delegate (string s) { return s.length == 5; }; Func<string, string> extract = delegate (string s) { return s; }; Func<string, string> project = delegate (string s) { return s.toupper(); }; IEnumerable<string> query = names.where(filter).orderby(extract).select(project);

확장메서드 (Extension Methods) 표준쿼리연산자를직접확장할경우사용 namespace System.Linq { using System; using System.Collections.Generic; public static class Enumerable { public static IEnumerable<T> Where<T>( this IEnumerable<T> source, Func<T, bool> predicate) { foreach (T item in source) if (predicate(item)) yield return item; } } }

LINQ to SQL: SQL Integration 테이블생성쿼리 클래스정의 create table People ( Name nvarchar(32) primary key not null, Age int not null, CanCode bit not null ) create table Orders ( OrderID nvarchar(32) primary key not null, Customer nvarchar(32) not null, Amount int ) [Table(Name="People")] public class Person { [Column(DbType="nvarchar(32) not null", Id=true)] public string Name; [Column] public int Age; [Column] public bool CanCode; } [Table(Name="Orders")] public class Order { [Column(DbType="nvarchar(32) not null", Id=true)] public string OrderID; [Column(DbType="nvarchar(32) not null")] public string Customer; [Column] public int Amount; }

LINQ to SQL (cont.) 구현코드 DataContext 는 LI NQ와 SQL을통합할수있게해주는중간개체이다. // establish a query context over ADO.NET sql connection DataContext context = new DataContext( "Initial Catalog=petdb;Integrated Security=sspi"); // grab variables that represent the remote tables that // correspond to the Person and Order CLR types Table<Person> custs = context.gettable<person>(); Table<Order> orders = context.gettable<order>(); // build the query var query = from c in custs from o in orders where o.customer == c.name select new { c.name, o.orderid, o.amount, c.age }; // execute the query foreach (var item in query) Console.WriteLine("{0} {1} {2} {3}", item.name, item.orderid, item.amount, item.age);

LINQ to SQL (cont.) 앞장의구현코드는다음 SQL 구문과동일 : SELECT [t0].[age], [t1].[amount], [t0].[name], [t1].[orderid] FROM [Customers] AS [t0], [Orders] AS [t1] WHERE [t1].[customer] = [t0].[name] 암시적으로형식이지정된지역변수 (implicitly typed local variables) 컴파일러가지역변수의타입을추론함 (Jscript 의 var 와비슷 ) 이런코드는에러가발생 : var 변수는특정메서드의경계를벗어날수없다. ( 필드, 혹은매개변수로사용불가 ) var integer = 1; integer = "hello";

LINQ to XML: XML Integration XML 데이터구현코드 : 혹은이런코드도사용할수있다 : 실제 XML 데이터 var e = new XElement("Person", new XAttribute("CanCode", true), new XElement("Name", "Loren David"), new XElement("Age", 31)); var e2 = XElement.Load(xmlReader); var e1 = XElement.Parse( @"<Person CanCode='true'> <Name>Loren David</Name> <Age>31</Age> </Person>"); <Person CanCode="true"> <Name>Loren David</Name> <Age>31</Age> </Person>

LINQ to XML (cont.) LINQ-XML 쿼리코드 1 var query = from p in people where p.cancode select new XElement("Person", new XAttribute("Age", p.age), p.name); LINQ-XML 쿼리코드 2 var x = new XElement("People", from p in people where p.cancode select new XElement("Person", new XAttribute("Age", p.age), p.name));

표준쿼리연산자목록 Operator Description Operator Description Where Select/SelectMany Take/Skip/ TakeWhile/SkipWhile Join/GroupJoin Restriction operator based on predicate function Projection operators based on selector function Partitioning operators based on position or predicate function Join operators based on key selector functions OfType/Cast SequenceEqual First/FirstOrDefault/Last/LastOrD efault/single/singleordefault Conversion operators to IEnumerable<T> based on filtering by or conversion to type argument Equality operator checking pairwise element equality Element operators returning initial/final/only element based on optional predicate function Concat Concatenation operator ElementAt/ElementAtOrDefault Element operators returning element based on position OrderBy/ThenBy/OrderByDesce nding/thenbydescending Sorting operators sorting in ascending or descending order based on optional key selector and comparer functions DefaultIfEmpty Element operator replacing empty sequence with default-valued singleton sequence Reverse Sorting operator reversing the order of a sequence Range Generation operator returning numbers in a range GroupBy Distinct Union/Intersect Grouping operator based on optional key selector and comparer functions Set operator removing duplicates Set operators returning set union or intersection Repeat Empty Any/All Generation operator returning multiple occurrences of a given value Generation operator returning an empty sequence Quantifier checking for existential or universal satisfaction of predicate function Except Set operator returning set difference Contains Quantifier checking for presence of a given element AsEnumerable ToArray/ToList ToDictionary/ToLookup Conversion operator to IEnumerable<T> Conversion operator to array or List<T> Conversion operators to Dictionary<K,T> or Lookup<K,T> (multidictionary) based on key selector function Count/LongCount Sum/Min/Max/Average Aggregate Aggregate operators counting elements based on optional predicate function Aggregate operators based on optional selector functions Aggregate operator accumulating multiple values based on accumulation function and optional seed

Thank you!