2
string[] filesHD = Directory.GetFiles(dirPath, filepattern1);

string[] filesDT = Directory.GetFiles(dirPath, filepattern2);

string[] filesTD = Directory.GetFiles(dirPath, filepattern3);

My 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]
puretppc
  • 3,232
  • 8
  • 38
  • 65

3 Answers3

5

There are several methods to do this, in C# the easiest is probably:

var allFiles = filesHD.Union(filesDT).Union(filesTD);

OR

var allFiles = filesHD.Concat(filesDT).Concat(filesTD);

You can end it with a call to .ToArray() if you will be enumerating it more than once, if you are just going to foreach over it once, don't worry about the .ToArray(). The difference between Union and Concat is Union uses the default equality comparer to ignore duplicates.

Pete Garafano
  • 4,863
  • 1
  • 23
  • 40
1

Could you try following code?

List<string> AllFiles = new List<string>();
AllFiles.Concat(filesHD);
AllFiles.Concat(filesDT);
AllFiles.Concat(filesTD);

var strAllFiles = AllFiles.ToArray();

Add reference: Using System.Linq;

Note: Typed without compiler, couldn't check for syntax errors.

Max
  • 12,622
  • 16
  • 73
  • 101
1

If you want to be simple, you could also try the following:

List<string> lstAllFiles=new List<string>();
lstAllFiles.AddRange(filesHD);
lstAllFiles.AddRange(filesDT);
lstAllFiles.AddRange(filesTD);
string[] strAllFiles=lstAllFiles.ToArray();

This method does not use Linq...
Hope this helps.

nurchi
  • 770
  • 11
  • 24