惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

量子位
Stack Overflow Blog
Stack Overflow Blog
人人都是产品经理
人人都是产品经理
The GitHub Blog
The GitHub Blog
Engineering at Meta
Engineering at Meta
Vercel News
Vercel News
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Y
Y Combinator Blog
The Cloudflare Blog
Last Week in AI
Last Week in AI
B
Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
T
Tailwind CSS Blog
V
Visual Studio Blog
博客园 - 三生石上(FineUI控件)
小众软件
小众软件
Google DeepMind News
Google DeepMind News
D
DataBreaches.Net
博客园 - 司徒正美
B
Blog RSS Feed
Microsoft Azure Blog
Microsoft Azure Blog
罗磊的独立博客
Hugging Face - Blog
Hugging Face - Blog
L
LangChain Blog

博客园 - J.D Huang

TinyDO:可能是WP首个支持中文语音识别的待办事项APP Internet TV 影音娱乐新生活 Windows Phone Developer Tools CTP 发布了! Python - 默认参数的一次性求值 Python小技巧 – True or False Python小技巧 - 子串查找 - J.D Huang 新的个人博客@ http://thinkbot.info MeeGo:下一个Android? Windows Mobile 6.5.3 Developer Tool Kit 发布了 塞班(Symbian)开源了(包括Symbian 3和S60等) Windows Mobile 6.5 SDK 发布了 (2月17日更新) C#4.0新特性之(三)协变与逆变 C#4.0新特性之(二)命名参数,可选参数与COM互操作 C#4.0新特性之(一)动态查找 Android手机防盗工具DroidGuard Simple HostMonitor 实用的网管小工具 Office Mobile 2010 Beta 发布了! - J.D Huang 试了一下.Net Fx 4.0中的Parallel - J.D Huang Lambda演算与科里化(Currying)
C#4.0新特性之(四)新的LINQ扩展方法-Zip()
J.D Huang · 2009-12-14 · via 博客园 - J.D Huang

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))

 以上代码会打印出

Freesc Huang
Joshua Guan
Ken Wang

在C#4.0中,我们可以看到一个类似的扩展函数[1]

代码2

        //
        
// 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程序: 

代码3

            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);
            }

 

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))

 

类似的,如果不考虑异常处理,C#的Zip扩展方法可以是如下实现[2]

代码5

    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);
        }
    }

4.总结

  Zip作为LINQ系统的新成员,提供了一种自由组合两个集合的方式,要注意的是,这个Zip使用时要求两个序列的长度一致,如果不一致,它会yield较短的长度。这一点和python中的zip是一样的。另外,您不妨可以试着写一个组合多个集合的MultiZip方法,也许它对您更加有用;-)

5.引用

[1] http://msdn.microsoft.com/en-us/library/dd267698(VS.100).aspx

[2] http://community.bartdesmet.net/blogs/bart/archive/2008/11/03/c-4-0-feature-focus-part-3-intermezzo-linq-s-new-zip-operator.aspx

AUTHOR: Freesc Huang @ CNBlogs