将foreach语句转换为for语句 [英] Convert foreach statement to for statement

查看:148
本文介绍了将foreach语句转换为for语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码中有一个要求,我需要在For循环中使用以下语句:

I have a requirement in my code where i need the below statement in For loop:

foreach (FileInfo fi in source_s.GetFiles())
{
   fi.CopyTo(Path.Combine(dest_d.ToString(), fi.Name), true);
}


如果有人知道,请帮帮我..


help me if anybody knows..

推荐答案

为避免重复调用GetFiles(),这可能会使您的应用程序运行速度大大降低,请一次获取文件在开始for循环之前.

To avoid repeated calls to GetFiles(), which could slow your application down considerably, get the files once before starting the for loop.

FileInfo[] foundFiles = source_s.GetFiles();
for (int i = 0; i < foundFiles.Length; i++)
{
  foundFiles[i].CopyTo(Path.Combine(dest_d.ToString(), foundFiles[i].Name), true);
}



甚至



or even

FileInfo[] foundFiles = source_s.GetFiles();
for (int i = 0; i < foundFiles.Length; i++)
{
  FileInfo fi = foundFiles[i];
  fi.CopyTo(Path.Combine(dest_d.ToString(), fi.Name), true);
}



首先,我不明白为什么要将foreach转换为for.

如果仍要执行此操作,则将所有文件的计数放入变量
然后运行for循环-
Firstly I dont see why you should be converting foreach to for.

If you still want to do it get the count of all files into a variable
and then run a for loop -
for(int i=0;i++,i<count)
{
      fi.CopyTo(Path.Combine(dest_d.ToString(), source_s.GetFiles()[i].Name), true);
}



其中count是文件列表.

我不确定{c1>是否可以正常工作,因为我不知道source_s.GetFiles()返回的是....



where count is the list of your files.

I''m not absolutely sure if source_s.GetFiles()[i].Name this work as I dont know what source_s.GetFiles() is returning....


这篇关于将foreach语句转换为for语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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