본문 바로가기
프로그래밍/C# LINQ

C# LINQ - Enumerable.Zip()

by bantomak 2024. 3. 5.

Enumerable.Zip<TFirst, TSecond, TResult>(IEnumerable<TFirst>, IEnumerable<TSecond>, Func<TFirst, TSecond, TResult>) 메서드

public static System.Collections.Generic.IEnumerable<TResult> Zip<TFirst,TSecond,TResult> (this
System.Collections.Generic.IEnumerable<TFirst> first, System.Collections.Generic.IEnumerable<TSecond> second, Func<TFirst,TSecond,TResult> resultSelector);

 

매개변수

first IEnumerable<TFirst>

병합할 첫 번째 시퀀스

 

second IEnumerable<TSecond>

병합할 두 번째 시퀀스

 

resultSelector Func<TFirst, TSecond, TResult>

두 시퀀스의 요소를 병합하는 방법을 지정하는 함수

 

반환

IEnumerable<TResult>

두 입력 시퀀스의 병합된 요소가 들어있는 IEnumerable<T>

 

예제 코드

int[] numbers = { 1, 2, 3, 4 };
string[] words = { "one", "two", "three" };

var numbersAndWords = numbers.Zip(words, (first, second) => first + " " + second);

foreach (var item in numbersAndWords)
    Console.WriteLine(item);

// This code produces the following output:

// 1 one
// 2 two
// 3 three

 

첫번째 시퀀스의 각 요소를 두 번째 시퀀스에서 동일한 인덱스가 있는 요소와 병합한다. 시퀀스에 동일할 수의 요소가 없는 경우 메서드는 시퀀스가 해당 요소 중 하나의 끝에 도달할 때까지 시퀀스를 병합한다. 예를 들어 한 시퀀스에 3개의 요소가 있고 다른 시퀀스에 4개의 요소가 있는 경우 결과 시퀀스에는 3개의 요소만 들어간다.

'프로그래밍 > C# LINQ' 카테고리의 다른 글

C# LINQ - Enumerable.TakeWhile  (0) 2024.03.28
C# 표준 질의 연산자(Standard Query Operators)  (1) 2024.02.26
C# Linq - Enumerable.Take()  (0) 2024.02.26
C# Linq - Enumerable.Reverse()  (0) 2024.02.19
C# Linq - Enumerable.OfType()  (1) 2024.02.16

댓글