简体   繁体   中英

iterate multiple lists with foreach in c#

I have arrays like these:

 var name = new[] { "matin", "mobin", "asghar" };
 var family = new[] { "shomaxe", "jjj", "reyhane" };
 var number = new[] { 1, 2, 3 };
 var age = new[] { 21, 23, 24 };

and I want to output them like this:

matin shomaxe 1 21
mobin jjj 2 23
asghar reyhane 3 24

how can I do that with a foreach loop ?
and how can I do it with a for loop ?

Considering your arrays are of equal length as you posted then below should work:

ForEach loop will need a counter variable to keep track of the position you are in the array as opposed to the For loop

ForEach loop

        int counter = 0;
        foreach(var item in name)
        {
            Console.WriteLine($"{item}, {family[counter]}, {number[counter]}, {age[counter]}");
            counter++;
        }

For loop

        for (int i = 0; i < name.Length; i++)
        {
            Console.WriteLine($"{name[i]}, {family[i]}, {number[i]}, {age[i]}");
        }

Yet another strange solution in fluent style with.Zip() operator:

var names = new[] { "matin", "mobin", "asghar" };
var families = new[] { "shomaxe", "jjj", "reyhane" };
var numbers = new[] { 1, 2, 3 };
var ages = new[] { 21, 23, 24 };

names
    .Zip(families, (name, family) => $"{name} {family}")
    .Zip(numbers, (res, number) => $"{res} {number}")
    .Zip(ages, (res, age) => $"{res} {age}")
    .ToList()
    .ForEach(x => Console.WriteLine(x));

From the docs about Zip operator.

If you want to avoid using an index you can use Zip from System.Linq to combine the lists together. Example below shows combining them into a Tuple (available from C# 7.0).

IEnumerable<(string a, string b, int c, int d)> iterable = name
    .Zip(family, (a, b) => (a, b))
    .Zip(number, (others, c) => (others.a, others.b, c))
    .Zip(age, (others, d) => (others.a, others.b, others.c, d));

foreach(var i in iterable)
{
    Console.WriteLine(i);
}

// Outputs:
// (matin, shomaxe, 1, 21)
// (mobin, jjj, 2, 23)
// (asghar, reyhane, 3, 24)

Supposing all of your arrays are of equal size:

   for(int i=0;i<name.Length;i++){
      Console.WriteLine("{0} {1} {2} {3}",name[i],family[i],number[i],age[i])
   }

I don't see how you can do this with a foreach however...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM