日期:2014-05-17  浏览次数:20921 次

怎样让嵌套的foreach语句中的内容一一对应
地图上有两个机场,乌鲁木齐和拉萨,窗体FormFind中有一个RichTextBox,Name属性为txtReadTxtStr,,E盘中有两个文件,1.txt和2.txt。我想实现的是点击乌鲁木齐时RichTextBox中显示1.txt中的内容,点击拉萨时显示2.txt中的内容,
  string[] cities = new string[] { "乌鲁木齐","拉萨"};
  string[] files = new string[] { @"e:\1.txt", @"e:\2.txt" };
  foreach (var city in cities)
  {  
  foreach (var file in files)
  {  
  using (StreamReader sr = new StreamReader(file, System.Text.Encoding.Default))
  {
  string TextStr;
  TextStr = sr.ReadToEnd().ToString();
  sr.Close();
  FormFind.txt += TextStr;
  }  
  }
  }
txt是我在FormFind窗体中定义的变量, public static string txt;this.txtReadTxtStr.Text=txt;也就是说怎样 让乌鲁木齐和1.txt对应,拉萨和2.txt对应,,上面的代码运行不出来结果,,请高手帮忙看看,,非常感谢,,

------解决方案--------------------
晕,然你传染了,犯了跟你一样的错误。

C# code
 string[] cities = new string[] { "乌鲁木齐","拉萨"};
  string[] files = new string[] { @"e:\1.txt", @"e:\2.txt" };
  for (var i=0; i<cities.Length; i++)
  {
    var city = cities[i];   
    if(city == txt)
    {
      var file= files[i];
      using (StreamReader sr = new StreamReader(file, System.Text.Encoding.Default))
      {
        .....
      }
      break;
    }   
  }