如何将3个字符串数组(包含文件)放入单个数组中 [英] how can I take 3 string arrays(contains files) into a single array
问题描述
string [] filesHD = Directory.GetFiles(dirPath,filepattern1);
string [] filesDT = Directory.GetFiles(dirPath,filepattern2);
string [] filesTD = Directory.GetFiles(dirPath,filepattern3);
这里filesHD []数组包含2个文件。 filesDT []包含2个文件,filesTD []也包含2个文件。我想创建一个单独的字符串数组,它将包含filesHD,filesDT,filesTD的所有6个文件。
string [] Allfiles = new string [filesHD + filesDT + filesTD]。
请帮帮我要做到这一点。
string[] filesHD = Directory.GetFiles(dirPath, filepattern1);
string[] filesDT = Directory.GetFiles(dirPath, filepattern2);
string[] filesTD = Directory.GetFiles(dirPath, filepattern3);
Here filesHD[] Array contains 2 files. filesDT[] contains 2 files and filesTD[] also contains 2 files. I want to create a single string Array which will contain all the 6 files of filesHD,filesDT,filesTD.
string[]Allfiles=new string [filesHD+filesDT+filesTD].
Please help me to do this.
推荐答案
主要问题应该是:为什么要将它们全部放在一个数组中?
此外,数组对象是 immutable (即使它们的元素是可变的),这使得它们不太适合保存可变长度的数据;为此,你应该更好地使用System.Collections.Generic
中的一些集合,比如System.Collections.Generic.List< string>
:
http://msdn.microsoft.com/en-us/library/System.Collections.Generic%28v=vs.110%29.aspx [ ^ ],
http://msdn.microsoft.com/en-us/library /6sh2ey19%28v=vs.110%29.aspx [ ^ ]。
您始终可以使用方法<$ c从列表中获取数组$ c> ToArray ,如果需要的话。
如果你还想立即从其他阵列创建数组(n)建议大多数情况下使用Array.Copy
:
http://msdn.microsoft.com/en-us/library/system.array.copy%28v=vs.110% 29.aspx [ ^ ]。
-SA
The main question should be: why putting them all in a single array?
Also, arrays objects are immutable (even though their elements are mutable), which makes them not very suitable for holding variable-length data; for this purpose, you should better use some collection fromSystem.Collections.Generic
, likeSystem.Collections.Generic.List<string>
:
http://msdn.microsoft.com/en-us/library/System.Collections.Generic%28v=vs.110%29.aspx[^],
http://msdn.microsoft.com/en-us/library/6sh2ey19%28v=vs.110%29.aspx[^].
You can always get an array from the list using the methodToArray
, if you need to.
If you still want to create the array immediately from other array(s) (not recommended for most cases), just useArray.Copy
:
http://msdn.microsoft.com/en-us/library/system.array.copy%28v=vs.110%29.aspx[^].
—SA
Linq [ ^ ]在这种情况下会有所帮助。
我会建议使用联盟 [ ^ ]声明。
Linq[^] would be helpful in this case.
I would suggest to use Union[^] statement.
string[] filesHD = {"file1.hd","file2.hd"};
string[] filesDT= {"file1.dt"," file2.dt"};
string[] filesTD = {"file1.td","file2.td"};
var allfiles=filesHD.Union(filesDT).Union(filesTD);
foreach(string file in allfiles)
{
Console.WriteLine("file: {0}", file);
}
注意:未经测试!
试试这个..
Try this..
List<string> lstTemp = new List<string>();
lstTemp.AddRange(filesHD);
lstTemp.AddRange(filesDT);
lstTemp.AddRange(filesTD);
string[] finalArray = lstTemp.ToArray();
注意:请使用System.Collections.Generic添加此命名空间;
参考:列出AddRange [ ^ ]
这篇关于如何将3个字符串数组(包含文件)放入单个数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!