JezB <je***********@blueyonder.co.uk> wrote:
What's the easiest way to concatenate arrays ? For example, I want a list of
files that match one of 3 search patterns, so I need something like
DirectoryInfo ld = new DirectoryInfo(searchDir);
pfiles = ld.GetFiles("*.aspx.resx|") + ld.GetFiles("*.ascx.resx") +
ld.GetFiles("*.master.resx");
but of course there is no + operation allowed on the FileInfo[] arrays
returned by the GetFiles method.
Do I have to read into 3 separate arrays then copy each entry one at a time
into a 4th array ?? yuk. Must be a neater way.
Well, you don't need to do things "one a a time" - you can use
Array.Copy to avoid that. Here's a sample which might help you. Note
that it doesn't try to deal with (or even detect) multi-dimensional
arrays, or those with a non-zero lower bound.
using System;
class Test
{
static void Main()
{
string[] first = {"hello", "there"};
string[] second = {"a", "b", "c"};
int[] third = {1, 2, 3};
// This will fail
// string[] ret = (string[]) ConcatenateArrays(first, second, third);
string[] ret = (string[]) ConcatenateArrays(first, second);
foreach (string x in ret)
{
Console.WriteLine (x);
}
}
static Array ConcatenateArrays(params Array[] arrays)
{
if (arrays==null)
{
throw new ArgumentNullException("arrays");
}
if (arrays.Length==0)
{
throw new ArgumentException("No arrays specified");
}
Type type = arrays[0].GetType().GetElementType();
int totalLength = arrays[0].Length;
for (int i=1; i < arrays.Length; i++)
{
if (arrays[i].GetType().GetElementType() != type)
{
throw new ArgumentException
("Arrays must all be of the same type");
}
totalLength += arrays[i].Length;
}
Array ret = Array.CreateInstance(type, totalLength);
int index=0;
foreach (Array array in arrays)
{
Array.Copy (array, 0, ret, index, array.Length);
index += array.Length;
}
return ret;
}
}
--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too