c# IEnumerable Zip
时间: 2025-02-21 22:20:12 浏览: 18
C# 中 IEnumerable
的 Zip
方法使用示例
定义与功能
Zip
扩展方法用于将两个序列中的对应元素配对并应用指定函数来生成新的序列。如果输入的两个序列长度不同,则只遍历到较短的那个序列结束为止[^3]。
使用场景
当有两个相同或不同类型的集合,并希望基于这两个集合创建一个新的组合数据集时,可以使用此方法。例如,合并名字列表和姓氏列表形成全名列表;或者结合日期范围及其对应的销售量等。
实际案例展示
下面是一个简单的例子,展示了如何利用 Zip
来连接两组整数数组:
using System;
using System.Collections.Generic;
using System.Linq;
class Program {
static void Main() {
List<int> numbersA = new List<int>{ 1, 2, 3 };
List<string> wordsB = new List<string>{"One", "Two", "Three"};
var combinedList = numbersA.Zip(wordsB, (n, w) => $"{n} -> {w}");
foreach(var item in combinedList){
Console.WriteLine(item);
}
}
}
这段程序将会输出:
1 -> One
2 -> Two
3 -> Three
这里定义了一个匿名函数 (n, w) => $"{n} -> {w}"
,它接收来自第一个枚举器 (numbersA
) 和第二个枚举器 (wordsB
) 的当前项作为参数,并返回一个字符串表示形式。
阅读全文
相关推荐



















