【问题标题】:iterate multiple lists with foreach in c#在 C# 中使用 foreach 迭代多个列表
【发布时间】:2021-03-28 15:43:41
【问题描述】:

我有这样的数组:

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

我想像这样输出它们:

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

如何使用 foreach 循环做到这一点?
以及如何使用 for 循环

【问题讨论】:

  • 给你:dotnetfiddle.net/jPhcWY。如果任何数组小于name 的长度,这将失败并返回IndexOutOfRageException,但由于您没有将处理定义为要求,这是最简单的解决方案。
  • 为什么不将数据结构更改为对象、结构或元组的列表或数组,每个人都持有?你现在拥有的是,假设是次优的。

标签: c# asp.net .net-core


【解决方案1】:

使用 .Zip() 运算符的流利风格的另一种奇怪解决方案:

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

来自关于 Zip 运算符的文档。

【讨论】:

    【解决方案2】:

    考虑到您的数组与您发布的长度相同,那么下面应该可以工作:

    ForEach 循环 需要一个计数器变量来跟踪您在数组中的位置,而不是 For 循环

    ForEach 循环

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

    for循环

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

    【讨论】:

      【解决方案3】:

      如果您想避免使用索引,您可以使用 System.Linq 中的 Zip 将列表组合在一起。下面的示例显示了将它们组合成一个元组(可从 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)
      

      【讨论】:

        【解决方案4】:

        假设所有数组的大小都相同:

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

        我不明白你如何使用 foreach 来做到这一点......

        【讨论】:

          猜你喜欢
          • 2011-01-22
          • 1970-01-01
          • 2010-12-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-05-05
          相关资源
          最近更新 更多