How to use Zip to combines elements from two arrays using Linq in C#

3 Answers

0 votes
using System;
using System.Linq;

class Program
{
    static void Main() {
        string[] people = { "Albus", "Arthur", "Alanna", "Avalon" };
        int[] ages = { 40, 51, 60, 45 };
        
        var result = people.Zip(ages, (p, e) => p + " " + e);
        
        foreach (var pair in result) {
            Console.WriteLine(pair);
        }
    }
}
  
 
 
  
/*
run:
  
Albus 40
Arthur 51
Alanna 60
Avalon 45

*/

 



answered Jul 4, 2023 by avibootz
0 votes
using System;
using System.Linq;

class Program
{
    static void Main() {
        var arr1 = new[] { 1, 2, 3, 4 };
        var arr2 = new[] { 8, 9, 0, 7 };

        var result = arr1.Zip(arr2, (x, y) => x * y);

        Console.WriteLine(string.Join(", ", result));
    }
}
  
 
 
  
/*
run:
  
8, 18, 0, 28

*/

 



answered Jul 4, 2023 by avibootz
0 votes
using System;
using System.Linq;

class Program
{
    static void Main() {
        int[] numbers = Enumerable.Range(1, 5).ToArray();
        string[] people = { "Albus", "Arthur", "Alanna", "Avalon" };

        var result = numbers.Zip(people, (n, p) => n + ": " + p);

        foreach (var pair in result) {
            Console.WriteLine(pair);
        }
    }
}
  
 
 
  
/*
run:
  
1: Albus
2: Arthur
3: Alanna
4: Avalon

*/

 



answered Jul 4, 2023 by avibootz

Related questions

1 answer 222 views
1 answer 216 views
1 answer 239 views
2 answers 259 views
1 answer 353 views
353 views asked Mar 10, 2021 by avibootz
1 answer 273 views
...