Zip() kết hợp hai chuỗi theo cặp (element-wise) cho đến khi một chuỗi hết. Trả về chuỗi kết quả từ hàm selector.
Ví dụ minh họa
Mảng số và mảng tên:
int[] intArray = { 1, 2, 3, 4, 5, 6, 7, 8 };
string[] stringArray = { "Depp", "Cruise", "Pitt", "Clooney", "Sandler", "Affleck", "Tarantino" };
Ghép cặp (số + " " + tên):
var mergedSeq = intArray.AsQueryable()
.Zip(stringArray, (one, two) => one + " " + two);
Mã nguồn hoàn chỉnh
using System;
using System.Linq;
using System.Collections.Generic;
public class Demo
{
public static void Main()
{
int[] intArray = { 1, 2, 3, 4, 5, 6, 7, 8 };
string[] stringArray = { "Depp", "Cruise", "Pitt", "Clooney", "Sandler", "Affleck", "Tarantino" };
var mergedSeq = intArray.AsQueryable()
.Zip(stringArray, (one, two) => one + " " + two);
foreach (var ele in mergedSeq)
Console.WriteLine(ele);
}
}
Kết quả đầu ra
1 Depp 2 Cruise 3 Pitt 4 Clooney 5 Sandler 6 Affleck 7 Tarantino
Lưu ý: intArray có 8 phần tử, stringArray có 7. Zip dừng ở 7 cặp. Phần tử 8 bị bỏ qua.
C# 7+ tuple syntax: .Zip(stringArray, (a, b) => (a, b)) trả về tuple.