位于另一个数组索引处的数组的值

本文关键字:数组 索引 另一个 | 更新日期: 2023-09-27 18:25:16

我有两个数组:string[]文件string[]注释

我正在使用foreach循环遍历文件数组。

foreach(string file in files)
{
comments.SetValue(//index of file we are at)
}

假设我得到一个文件,它是文件数组的索引20。我想做的是能够在同一索引处获得注释数组的值。因此,对于文件[0],我返回comments[0]、文件[1]comments[1]等。

位于另一个数组索引处的数组的值

我会像这个一样做

for (int i = 0; i < files.Length; i++) {
   string file = files[i];
   string comment = comments[i];
}

简单地执行:

string[] files = { "1", "2", "3" };
            string[] comments = {"a","b","c"};
            int i = 0;
            foreach (string file in files)
            {
                 files[i]  = comments[i] ;
                 i++;
            }

您可以使用IndexOf,假设重复不会成为的问题

foreach(string file in files)
{
    int index = files.IndexOf(file);
    //blah blah
}

但使用for循环可能会更容易、更高效,然后你就会有索引

   for (var i = 0; i < files.Length; i++)

不要使用foreach,而是使用for

for (var i = 0; i < files.Length; i++)
{
  // ...
}

您可以使用.Zip()进行以下操作:

foreach(var fc in files.Zip(comments, (f, c) => new { File = f, Comment = c }))
{
    Console.WriteLine(fc.File);
    Console.WriteLine(fc.Comment);
}