LINQ 소개 (Introduction to LINQ)
LINQ(Language Integrated Query)는 C# 언어에서 데이터 쿼리를 위한 통합된 구문을 제공하는 기능입니다. LINQ를 사용하면 다양한 데이터 소스(예: 배열, 컬렉션, XML, 데이터베이스 등)에 대해 일관된 방식으로 데이터를 쿼리하고 조작할 수 있습니다. LINQ는 쿼리 구문(Query Syntax)과 메서드 구문(Method Syntax)을 모두 지원합니다.
LINQ 기본 구문 (Basic LINQ Syntax)
LINQ 쿼리는 from, where, select 키워드를 사용하여 작성됩니다.
예제: 기본 LINQ 쿼리 (Basic LINQ Query)
using System;
using System.Linq;
namespace LINQExample
{
class Program
{
static void Main(string[] args)
{
int[] numbers = { 2, 4, 6, 8, 10, 12 };
// LINQ 쿼리 구문 (Query Syntax)
var evenNumbersQuery = from number in numbers
where number % 2 == 0
select number;
Console.WriteLine("Even Numbers (Query Syntax):");
foreach (var num in evenNumbersQuery)
{
Console.WriteLine(num);
}
// LINQ 메서드 구문 (Method Syntax)
var evenNumbersMethod = numbers.Where(n => n % 2 == 0);
Console.WriteLine("Even Numbers (Method Syntax):");
foreach (var num in evenNumbersMethod)
{
Console.WriteLine(num);
}
}
}
}
LINQ와 컬렉션 (LINQ with Collections)
LINQ는 배열뿐만 아니라 컬렉션에서도 사용할 수 있습니다.
예제: LINQ와 리스트 (LINQ with List)
using System;
using System.Collections.Generic;
using System.Linq;
namespace LINQExample
{
class Program
{
static void Main(string[] args)
{
List<string> names = new List<string> { "Alice", "Bob", "Charlie", "David" };
// 이름이 'B'로 시작하는 이름 필터링 (Filtering names starting with 'B')
var filteredNames = from name in names
where name.StartsWith("B")
select name;
Console.WriteLine("Names starting with 'B':");
foreach (var name in filteredNames)
{
Console.WriteLine(name);
}
}
}
}
LINQ 연산자 (LINQ Operators)
LINQ에는 다양한 연산자가 있습니다. 이들 연산자는 필터링, 정렬, 그룹화, 조인 등을 수행할 수 있습니다.
예제: LINQ 연산자 사용 (Using LINQ Operators)
using System;
using System.Linq;
namespace LINQExample
{
class Program
{
static void Main(string[] args)
{
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// 필터링 (Filtering)
var evenNumbers = numbers.Where(n => n % 2 == 0);
// 정렬 (Sorting)
var sortedNumbers = numbers.OrderByDescending(n => n);
// 선택 (Selecting)
var squaredNumbers = numbers.Select(n => n * n);
// 출력 (Output)
Console.WriteLine("Even Numbers:");
foreach (var num in evenNumbers)
{
Console.WriteLine(num);
}
Console.WriteLine("Sorted Numbers:");
foreach (var num in sortedNumbers)
{
Console.WriteLine(num);
}
Console.WriteLine("Squared Numbers:");
foreach (var num in squaredNumbers)
{
Console.WriteLine(num);
}
}
}
}
LINQ와 데이터베이스 (LINQ with Database)
LINQ는 데이터베이스와도 통합할 수 있습니다. LINQ to SQL이나 Entity Framework를 사용하면 SQL 데이터베이스를 쿼리할 수 있습니다.
예제: Entity Framework를 사용한 LINQ (LINQ with Entity Framework)
using System;
using System.Linq;
using System.Data.Entity;
namespace LINQExample
{
public class Product
{
public int ProductId { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
public class ProductContext : DbContext
{
public DbSet<Product> Products { get; set; }
}
class Program
{
static void Main(string[] args)
{
using (var context = new ProductContext())
{
// 데이터베이스에서 50달러 이상인 제품 검색 (Querying products with price over 50 dollars)
var expensiveProducts = from product in context.Products
where product.Price > 50
select product;
Console.WriteLine("Expensive Products:");
foreach (var product in expensiveProducts)
{
Console.WriteLine($"{product.Name}: ${product.Price}");
}
}
}
}
}
LINQ와 XML (LINQ to XML)
LINQ를 사용하여 XML 데이터를 쿼리하고 조작할 수 있습니다.
예제: LINQ to XML
using System;
using System.Linq;
using System.Xml.Linq;
namespace LINQExample
{
class Program
{
static void Main(string[] args)
{
string xmlData = @"
<Books>
<Book>
<Title>LINQ in Action</Title>
<Author>Fabrice Marguerie</Author>
</Book>
<Book>
<Title>Pro LINQ</Title>
<Author>Joe Rattz</Author>
</Book>
</Books>";
XDocument xdoc = XDocument.Parse(xmlData);
// XML 데이터에서 제목 검색 (Querying Titles from XML)
var titles = from book in xdoc.Descendants("Book")
select book.Element("Title").Value;
Console.WriteLine("Book Titles:");
foreach (var title in titles)
{
Console.WriteLine(title);
}
}
}
}
LINQ 메서드 구문과 쿼리 구문 비교 (Method Syntax vs Query Syntax)
LINQ에는 메서드 구문과 쿼리 구문 두 가지 스타일이 있습니다. 두 구문은 동일한 작업을 수행하지만, 작성 방식이 다릅니다.
예제: 메서드 구문과 쿼리 구문 비교 (Comparison of Method Syntax and Query Syntax)
using System;
using System.Linq;
namespace LINQExample
{
class Program
{
static void Main(string[] args)
{
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// 쿼리 구문 (Query Syntax)
var querySyntax = from number in numbers
where number % 2 == 0
orderby number descending
select number;
// 메서드 구문 (Method Syntax)
var methodSyntax = numbers.Where(n => n % 2 == 0)
.OrderByDescending(n => n);
Console.WriteLine("Query Syntax:");
foreach (var num in querySyntax)
{
Console.WriteLine(num);
}
Console.WriteLine("Method Syntax:");
foreach (var num in methodSyntax)
{
Console.WriteLine(num);
}
}
}
}
결론 (Conclusion)
LINQ는 다양한 데이터 소스를 일관된 방식으로 쿼리하고 조작할 수 있는 강력한 도구입니다. LINQ의 쿼리 구문과 메서드 구문을 이해하고, 다양한 연산자와 데이터 소스에서의 사용법을 익히는 것이 중요합니다. LINQ를 통해 C#에서 데이터 처리를 효율적이고 간결하게 구현할 수 있습니다.
