2014-10-02 50 views
-2

的阵列的我有两个阵列:串[]文件串[]评论值在索引的另一阵列

我通过文件循环使用foreach循环阵列。

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

说我得到一个文件,该文件是索引20的文件数组。我想要做的就是在相同的索引处获取comments数组的值。因此,对于文件的[0]我返回评论[0],文件[1]评论[1]等等等等

+0

考虑使用'词典<字符串,字符串>',也许。 – 2014-10-02 09:28:06

回答

2

我会做这样的

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

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

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

但它可能会可以更容易,更有效地使用一个for循环,那么你将有指数

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

不要使用foreach,使用for代替:

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

做简单:

string[] files = { "1", "2", "3" }; 
      string[] comments = {"a","b","c"}; 

      int i = 0; 
      foreach (string file in files) 
      { 
       files[i] = comments[i] ; 
       i++; 
      } 
0

您可以使用此.Zip()

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