본문 바로가기

프로그래밍/C# LINQ14

C# Linq - Enumerable.Where() Enumerable.Where(IEnumerable, Func) 메서드 public static System.Collections.Generic.IEnumerable Where(this System.Collections.Generic.IEnumerable source,Func predicate); 매개변수 source IEnumerable 필터링할 IEnumerable predicate Func 각 요소를 조건에 대해 테스트하는 함수 특정 조건으로 필터링해서 해당 조건에 부합하는 요소들만 취합하고 싶을 때 사용한다. 예제 코드 List fruits = new List { "apple", "passionfruit", "banana", "mango", "orange", "blueberry", "grape",.. 2024. 2. 15.
C# Linq - Enumerable.All() Enumerable.All(IEnumerable, Func) 메서드 public static bool All (this System.Collections.Generic.IEnumerable source, Func predicate); 매개변수 source IEnumerable predicate를 적용할 항목들을 가지고 있는 IEnumerable predicate Func 각 항목에 적용할 조건을 가진 함수 반환값 true - 모든 항목들이 predicate에 설정한 테스트를 통과하면 true를 반환한다. 또는 시퀀스가 empty일 경우 false - 그 이외의 경우 false를 반환한다. predicate를 통해서 모든 항목에 대한 특정한 테스트를 진행하고 이에 대한 결과를 확인하고 싶을때 사용한다. 예.. 2024. 2. 15.
C# Linq - Enumerable.Range() Enumerable.Range(Int32, Int32) 메서드 public static System.Collections.Generic.IEnumerable Range (int start, int count); 매개변수 start int32 시퀀스의 첫번째 정수값 (시작값) count int32 생성할 순차적 정수의 개수 특정 시작값에서부터 순차적으로 정수를 생성하고 싶을때 사용한다. 정리하자면 Enumerable.Range(0, 5); 라고 한다면 0, 1, 2, 3, 4 로 정수의 나열이 생성된다. 예제 코드 // Generate a sequence of integers from 1 to 10 // and then select their squares. IEnumerable squares = Enum.. 2023. 12. 18.
C# Linq - Enumerable.Aggregate() Aggregate() 합계, 총액이라는 의미로 생각하면 이해하기가 편하다. 누적 연산을 할 때 쓰면 유용하다. 정리하자면, 리스트의 요소들을 하나의 값으로 변환한다. 함수형 프로그래밍에는 Fold(), Reduce()와 같은 함수들이 비슷한 기능을 한다. 문자열 모아서 출력하기 각각의 요소들을 이어 붙여서 하나의 문자열로 출력이 가능하다. public class Program { static void Main(string[] args) { string[] list = {"kim", "lee", "park", "choi", "dol"}; var data = list.Aggregate((str1, str2) => str1 + ", " + str2); Console.WriteLine(data); } } 숫자 .. 2023. 6. 26.
C# Linq - Enumerable.OrderBy() OrderBy()로 정렬하기 OrderBy()를 호출하면 해당하는 데이터를 기준으로 오름차순(Ascending) 정렬한다. 내림차순으로 정렬이 필요한 경우 내림차순(OrderByDescending)으로 메서드를 호출한다. ThenBy()를 추가해서 세부정렬하기 2023. 6. 20.
C# Select vs SelectMany Select() 메서드 객체에 담긴 여러 데이터 중에서 원하는 부분만 손쉽게 추출하여 새로운 형태의 컬렉션으로 생성한다. public class Program { public class Winner { public string name; public int[] years; } public static void Main() { List list = new() { new Winner() { name = "Boston", years = new [] { 1989, 1999 } }, new Winner() { name = "Yankees", years = new [] { 2000, 2012, 2013, 2018 } }, new Winner() { name = "Newyork", years = new [] { 19.. 2023. 6. 19.