일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | |||
5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 |
26 | 27 | 28 | 29 | 30 | 31 |
- User Stack
- 알고리즘수업-너비우선탐색2
- pintos
- 티스토리챌린지
- KRAFTON JUNGLE
- 핀토스
- 파이썬
- BFS
- 크래프톤 정글
- TiL
- 오블완
- 크래프톤 정글 4기
- 크래프톤정글4기
- Unity
- 알고리즘
- 추상클래스와인터페이스
- 다익스트라
- 4기
- C
- project3
- c#
- 크래프톤정글
- anonymous page
- 유니티
- 전쟁-전투
- 백준
- kraftonjungle
- 네트워크
- 이벤트 함수 실행 순서
- 연결리스트
- Today
- Total
말감로그
[C#] 고급 문법 LinQ(링큐) 알아보기 본문
링큐
링큐는 데이터를 쿼리처럼 쉽게 조작하고 필터링할 수 있도록 해주는 기능이다.
링큐의 기본적인 3가지 키워드
- from : 어떤 데이터 집합에서 데이터를 찾을 것인가?
- where : 어떤 조건의 데이터를 찾을 것인가?
- select : 어떤 값을 추출할 것인가?
+ orderby : 정렬 기준 (오름차순) / orderByDescending (내림차순)
1. 쿼리 구문 기본 구조
from 변수 in 컬렉션
where 조건
orderby 정렬기준
select 결과
ex) 짝수만 추출
int[] numbers = { 1, 2, 3, 4, 5, 6 };
var evenNumbers = from n in numbers
where n % 2 == 0
select n;
foreach (var num in evenNumbers)
{
Console.WriteLine(num); // 출력: 2 4 6
}
2. 메서드 구문
점(.) 연산자로 연결해서 사용
1. 메서드 구문 기본 구조
컬렉션.메서드(람다식)
ex) 짝수만 추출
int[] numbers = { 1, 2, 3, 4, 5, 6 };
var evenNumbers = numbers.Where(n => n % 2 == 0);
foreach (var num in evenNumbers)
Console.WriteLine(num); // 2, 4, 6 출력
3. LinQ의 주요 연산자
- Where : 조건에 맞는 요소 필터링
List<int> numbers = new List<int> { 1,2,3,4,5,6,7,8,9,10 };
var evenNumbers = numbers.Where(n => n % 2 == 0);
// 결과 : 2, 4, 6, 8, 10
- Select : 각 요소를 다른 형태로 변환
List<string> names = new List<string> { "Alice", "Bob", "Charlie" };
var lengths = names.Select(name => name.Length);
// 결과 : 5, 3, 7
- OrderBy / OrderByDescending: 요소를 오름차순 또는 내림차순으로 정렬
List<string> fruits = new List<string> = { "apple", "banana", "cherry" };
var sortedFruits = fruits.OrderBy(f => f.Length);
// 결과 : apple, cherry, banana
- GroupBy : 특정 키를 기준으로 요소를 그룹화한다.
List<Person> people = new List<Person>
{
new Person { Name = "Alice" , Age = 25 },
new Person { Name = "Bob" , Age = 30 },
new Person { Name = "Charlie" , Age = 25 }
};
var groupedByAge = people.GroupBy(p => p.Age);
// 결과 : 25: [Alice, Charile], 30: [Bob]
- Join : 두 컬렉션을 결합한다.
List<Student> students = new List<Student>
{
new Student { Id = 1 , Name = "Alice" },
new Student { Id = 2 , Name = "Bob" }
};
List<Score> scores = new List<Score>
{
new Score { StudentId = 1 , MathScore = 90 },
new Score { StudentId = 2 , MathScore = 85 }
};
var query = students.Join(scores,
student => student.Id,
score => score.StudentId,
(student, score) => new { student.Name, score.MathScore });
// 결과 : Alice : 90 , Bob : 85
- First / FirstOrDefault : 조건을 만족하는 첫 번째 요소를 반환한다. FirstOrDefault는 요소가 없을 경우 기본값을 반환한다.
List<int> numbers = new List<int> { 1, 2, 3, 4, 5};
int firstEven = numbers.First(n => n % 2 == 0); // 2
int firstOver10 = numbers.FirstOrDefault(n => n < 10); // 0
- Any / All : Any는 조건을 만족하는 요소가 하나라도 있는지, All은 모든 요소가 조건을 만족하는지 확인
bool hasEven = numbers.Any(n => n % 2 == 0); // true
bool allPositive = numbers.All(n => n > 0); // true
- Count : 조건을 만족하는 요소의 개수를 반환한다.
int evenCount = numbers.Count(n => n % 2 == 0); // 2
- Sum / Average / Min / Max: 숫자 컬렉션에 대한 계산을 수행한다.
int sum = numbers.Sum(); // 15
double average = numbers.Average(); // 3
int min = numbers.Min(); // 1
int max = numbers.Max(); // 5
- Distinct : 중복을 제거
List<int> numbers = new List<int> { 1,2,3,3,3 };
var distinct = numbers.Distinct();
// 결과 : 1, 2, 3
- ThenBy() : 이미 정렬 한 다음의 순서에 대해 더 추가 조건으로 정렬할 수 있도록 하는 함수
이러한 Linq 연산자들을 조합하여 복잡한 데이터 처리 작업을 간결하고 효과적으로 수행할 수 있다.
플레이어 데이터 필터링, 아이템 정렬, 스코어 계산 등 다양한 상황에서 활용할 수 있다.
장점
1. 간결한 코드로 인해 코드의 가독성이 높다
2. 컴파일 시점에 오류를 검출하기 때문에 타입 안정성
주의사항
1. 성능 : 복잡한 LINQ 쿼리는 성능에 영향을 줄 수 있음
2. 지연 실행 : 대부분의 LINQ 연산은 실제 데이터가 필요할 때까지 실행을 지연함
'언어 > C#' 카테고리의 다른 글
[C#] 가비지 컬렉터(GC) 동작 원리 (4) | 2025.08.09 |
---|---|
C# vs C++ (0) | 2025.04.04 |
Unity C# 기초 4. 제어문 if문 (조건문, 분기문) (0) | 2023.05.10 |
Unity C# 기초 3. 멤버변수, 지역변수 (1) | 2023.05.10 |
Unity C# 기초 2. 형변환(casting) (0) | 2023.05.10 |