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!