C#4.0新特性之(四)新的LINQ扩展方法-Zip()
C#4.0新特性之(四)新的LINQ扩展方法-Zip()
1.简介
所谓zip(中文有拉链的意思),就是像拉链一样,把两个list缝合在一起。Python中有个zip函数可以用来方便的合并两个或者多个集合,例如:
>>> firstName=['Freesc','Joshua','Ken']
>>> lastName=['Huang','Guan','Wang']
>>> for f,l in zip(firstName,lastName):
print('{0} {1}'.format(f,l))
>>> lastName=['Huang','Guan','Wang']
>>> for f,l in zip(firstName,lastName):
print('{0} {1}'.format(f,l))
以上代码会打印出
Freesc Huang
Joshua Guan
Ken Wang
在C#4.0中,我们可以看到一个类似的扩展函数[1]:

//
// Summary:
// Merges two sequences by using the specified predicate function.
//
// Parameters:
// first:
// The first sequence to merge.
//
// second:
// The second sequence to merge.
//
// resultSelector:
// A function that specifies how to merge the elements from the two sequences.
//
// Type parameters:
// TFirst:
// The type of the elements of the first input sequence.
//
// TSecond:
// The type of the elements of the second input sequence.
//
// TResult:
// The type of the elements of the result sequence.
//
// Returns:
// An System.Collections.Generic.IEnumerable<T> that contains merged elements
// of two input sequences.
public static IEnumerable<TResult> Zip<TFirst, TSecond, TResult>(this IEnumerable<TFirst> first,
IEnumerable<TSecond> second,
Func<TFirst, TSecond, TResult> resultSelector);
// Summary:
// Merges two sequences by using the specified predicate function.
//
// Parameters:
// first:
// The first sequence to merge.
//
// second:
// The second sequence to merge.
//
// resultSelector:
// A function that specifies how to merge the elements from the two sequences.
//
// Type parameters:
// TFirst:
// The type of the elements of the first input sequence.
//
// TSecond:
// The type of the elements of the second input sequence.
//
// TResult:
// The type of the elements of the result sequence.
//
// Returns:
// An System.Collections.Generic.IEnumerable<T> that contains merged elements
// of two input sequences.
public static IEnumerable<TResult> Zip<TFirst, TSecond, TResult>(this IEnumerable<TFirst> first,
IEnumerable<TSecond> second,
Func<TFirst, TSecond, TResult> resultSelector);
它可以用来合并列表,并且提供了自定义的组合规则:Func<TFirst, TSecond, TResult> resultSelector。
2.示例
下面是一段和代码1功能一样的C#4.0程序:

List<String> firstName = new List<String> { "Freesc", "Joshua", "Ken" };
List<String> lastName = new List<String> { "Huang", "Guan", "Wang" };
foreach (var name in firstName.Zip(lastName, (fname, lname) => fname + " " + lname))
{
Console.WriteLine(name);
}
List<String> lastName = new List<String> { "Huang", "Guan", "Wang" };
foreach (var name in firstName.Zip(lastName, (fname, lname) => fname + " " + lname))
{
Console.WriteLine(name);
}
3.Zip()的实现
在python中要实现一个zip,很简单(这里省去了异常处理),只需要用到三个内建函数,iter,map和next:
def zip(*iterables):
# zip('ABCD', 'xy') --> Ax By
iterables = map(iter, iterables)
while iterables:
yield tuple(map(next, iterables))
# zip('ABCD', 'xy') --> Ax By
iterables = map(iter, iterables)
while iterables:
yield tuple(map(next, iterables))
类似的,如果不考虑异常处理,C#的Zip扩展方法可以是如下实现[2]:

static class Enumerable
{
public static IEnumerable<TResult> Zip<TFirst, TSecond, TResult>(this IEnumerable<TFirst> first,
IEnumerable<TSecond> second,
Func<TFirst, TSecond, TResult> func)
{
var ie1 = first.GetEnumerator();
var ie2 = second.GetEnumerator();
while (ie1.MoveNext() && ie2.MoveNext())
yield return func(ie1.Current, ie2.Current);
}
}
{
public static IEnumerable<TResult> Zip<TFirst, TSecond, TResult>(this IEnumerable<TFirst> first,
IEnumerable<TSecond> second,
Func<TFirst, TSecond, TResult> func)
{
var ie1 = first.GetEnumerator();
var ie2 = second.GetEnumerator();
while (ie1.MoveNext() && ie2.MoveNext())
yield return func(ie1.Current, ie2.Current);
}
}
4.总结
Zip作为LINQ系统的新成员,提供了一种自由组合两个集合的方式,要注意的是,这个Zip使用时要求两个序列的长度一致,如果不一致,它会yield较短的长度。这一点和python中的zip是一样的。另外,您不妨可以试着写一个组合多个集合的MultiZip方法,也许它对您更加有用;-)
5.引用
[1] http://msdn.microsoft.com/en-us/library/dd267698(VS.100).aspx
AUTHOR: Freesc Huang @ CNBlogs
分类:
C#
posted on 2009-12-14 13:57 J.D Huang 阅读(5314) 评论(0) 编辑 收藏 举报
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· [AI/GPT/综述] AI Agent的设计模式综述