在foreach循环中加入字符串

问题描述:

string[] drives = Directory.GetLogicalDrives();
foreach (string d in drives)
{
string[] d1 = Directory.GetDirectories(d);
string[] pathlist = fde.Union(falaa).Union(d1).ToArray();
}

//fde is the nother path list
//falaa is the nother path list
* pathlist is the collection of all lists

//in path list i am not able to store the list

嗯......那里有一些奇怪的代码。



每次绕过循环,你会收集一些信息,并立即丢弃它 - 当你的数据超出范围时,你的数据都不可用于循环之外当循环结束时,或者当你用新变量覆盖它时可用于下一次迭代 - 所以整个循环当前是多余的并且可以被删除。



我是不完全确定你要做什么,但首先,将第一个联盟移到外面e循环,因为什么都不会改变它:

Um...That's some odd code you have there.

Each time you go round the loop, you collect some information, and immediately throw it away - none of your data is available outside the loop as it goes out of scope when the loop ends, or available to the next iteration as you overwrite it with new variables - so the whole loop is currently redundant and can be removed.

I'm not exactly sure what you are trying to do, but to start with, move the first union outside the loop as nothing will change it:
string[] drives = Directory.GetLogicalDrives();
string[] listPaths = fde.Union(falaa).ToArray();
foreach (string d in drives)
    {
    string[] d1 = Directory.GetDirectories(d);
    string[] pathlist = listPaths.Union(d1).ToArray();
    }

然后,我在组装时创建一个外部列表来保存数据:

Then, I'd create an external list to hold the data while I was assembling it:

string[] drives = Directory.GetLogicalDrives();
string[] listPaths = fde.Union(falaa).ToArray();
List<string> paths = new List<string>();
foreach (string d in drives)
    {
    string[] d1 = Directory.GetDirectories(d);
    paths.AddRange(listPaths.Union(d1));
    }

然后在循环外可以使用路径集合。

The paths collection is then available outside the loop.