C# - 如何使用循环用其索引填充每个数组元素? [英] C# - how do I use a loop to populate each array element with its index?

查看:103
本文介绍了C# - 如何使用循环用其索引填充每个数组元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





虽然一些YouTube视频给了我很多帮助,但我无法理解阵列,收藏品和列表。如何使用循环用其索引填充每个数组元素?我尝试过使用foreach循环和for循环,但都没有工作。请看下面我尝试过的内容。



亲切的问候



我尝试过:



Hi,

I am having trouble getting my head around arrays, collections and lists although some YouTube videos have helped me a lot. How do I use a loop to populate each array element with its index? I have tried using a foreach loop and a for loop, but neither are working. Please see what I have tried below.

Kind regards

What I have tried:

public static int[] PopulateArray(int[] array)
     {

         foreach (int something in array)
         {

             return something;
         }


     }
 }







public static int[] PopulateArray(int[] array)
      {
          for (int i = 0; ; i++)
          {

              return array;
          }
      }
  }

推荐答案

你做不到a foreach - 它需要是for循环:

You can't do it with a foreach - it needs to be a for loop:
public static int[] PopulateArray(int[] array)
      {
          for (int i = 0; i < array.Length; i++)
          {
              array[i] = i;
          }
      return array
      }


这篇关于C# - 如何使用循环用其索引填充每个数组元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆