C#4.0新特性之(四)新的LINQ擴充方法-Zip()

來源:互聯網
上載者:User

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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.