LINQ zip

LINQ系列

zip其實在一般案子當中,還滿少見,這個用法是將兩個物件合併起來

來個小小sample一下

            int[] numArr1 = { 1, 3, 5,7 };     
            int[] numArr2 = { 2, 4, 6,10 }; 
            var collection = numArr1.Zip(numArr2, (a, b) => a * b);
            foreach (var n in collection)
            {
                Console.WriteLine(n);
            }
            //2
            //12
            //30
            //70

加點變化一下
假設我要把這兩者合併起來
 

            int[] numbers = { 1, 2, 3 };
            string[] words = { "李一", "兆二", "張三" };
            IEnumerable<string> zip = numbers.Zip(words, (n, w) =>"學號:" + n + " 姓名:" + w);
            foreach (var item in zip)
            {
                Console.WriteLine(item);
            }

早期的程式,大部分都是用一些什麼迴圈方式去進行處理的部分來解決,遇到合併的時候,可以考慮用zip方式進行合併。
 

老E隨手寫