■개요
LINQ(Language INtergrated Query : 통합 언어 쿼리)는 복수의 데이터에서 조건에 맞는 데이터를 간추린 데이터들을 얻을 수 있도록 해주는 C#의 문법으로, .Net Framework 3.5부터 도입되었다고 한다.
■샘플코드
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace HelloWorldCore
{
/// <summary>
/// 학생 클래스
/// </summary>
class Student
{
public string name { get; set; }
public int age { get; set; }
public int grade { get; set; }
}
/// <summary>
/// Linq 사용법
/// </summary>
class LinqPractice
{
private int studentNumber = 5;
private string[] studentNames = { "홍길동", "황진이", "이순신", "장영실", "정약용" };
private int[] studentAges = { 25, 26, 25, 30, 40 };
private int[] studentGrades = { 4, 4, 4, 2, 1 };
// 학생 리스트
List<Student> students = new List<Student>();
public LinqPractice()
{
CreateStudents();
}
private void CreateStudents()
{
// 학생 객체를 생성하여 학생 리스트에 추가한다.
for (int i = 0; i < studentNumber; i++)
{
Student student = new Student();
student.name = studentNames[i];
student.age = studentAges[i];
student.grade = studentGrades[i];
students.Add(student);
}
}
/// <summary>
/// LINQ구문은 from ~ where ~ select 순서로 작성한다.
/// LIST, DataSource, Database, Collection, Array등을 LINQ로 사용할 수 있다.
/// from, where, order by, select, group by, join등의 구문을 사용할 수 있다.
/// </summary>
public void TestLinq()
{
// 20대 학생만을 조회하여 얻어오는 Linq구문
var Twenty_Student = from _student in students
where _student.age >= 20 && _student.age < 30
orderby _student.age ascending
select _student;
// 30대 학생만을 조회하여 얻어오는 Linq구문
var Thirty_Student = from _student in students
where _student.age >= 30 && _student.age < 40
orderby _student.age ascending
select _student;
foreach(var Student in Twenty_Student)
{
Console.WriteLine("20대 학생은 = {0} 입니다.", Student.name);
}
Console.WriteLine();
foreach (var Student in Thirty_Student)
{
Console.WriteLine("30대 학생은 = {0} 입니다.", Student.name);
}
}
}
}
■참조
afsdzvcx123.tistory.com/entry/C-LINQ-%EC%86%8C%EA%B0%9C-%EB%B0%8F-%EC%82%AC%EC%9A%A9%EB%B2%95
[C#] LINQ 소개 및 사용법
이번 포스팅에서는 C# 문법 중 하나인, LINQ에 대해 알아보도록 하겠습니다. LINQ란 Language-Intergreated Query의 약자?로써, .NET Framework 버전 3.5부터 도입이 되었습니다. 그냥 쉽게 간단히 얘기해 C#에서..
afsdzvcx123.tistory.com
반응형
'■ 프로그래밍 언어 > C#' 카테고리의 다른 글
WPF (0) | 2021.03.17 |
---|---|
pdb 파일 (0) | 2021.03.15 |
비동기처리1 - Thread, Task (0) | 2021.01.07 |
DLL이란? (0) | 2020.12.09 |