Concatenating Dynamic Arrays

Another day another unit test and another extension to my little TArrayEx class. This time I found myself having to concatenate some dynamic arrays. After solving the problem for the particular array type I decided to produce a generic solution. Here's the method I came up with:

type
  TArrayEx = class(TObject)
  public
    ...
    class function Concat<T>(const Arrays: array of TArray<T>): TArray<T>;
    ...
  end;

The method takes an array of the arrays you want to concatenate (don't forget the [] notation) and returns the concatenated array. Here's an example where the resultant array A contains the integers 1 to 10 in order:

var
  A, A1, A2, A3: TArray<Integer>;
begin
  A1 := TArray<Integer>.Create(1, 2, 3);
  A2 := TArray<Integer>.Create(4, 5, 6);
  A3 := TArray<Integer>.Create(7, 8, 9, 10);
  A := TArrayEx.Concat<Integer>([A1, A2, A3]);
  ...
end;
Here is the implementation:
class function TArrayEx.Concat<T>(const Arrays: array of TArray<T>): TArray<T>;
var
  A: TArray<T>;
  ResLen: Integer;
  ResIdx, Idx: Integer;
begin
  ResLen := 0;
  for A in Arrays do
    Inc(ResLen, Length(A));
  SetLength(Result, ResLen);
  ResIdx := 0;
  for A in Arrays do
  begin
    for Idx := Low(A) to High(A) do
    begin
      Result[ResIdx] := A[Idx];
      Inc(ResIdx);
    end;
  end;
end;

My other blogs about TArrayEx and working with dynamic arrays are:

Comments

  1. Anonymous3:11 pm

    Hi, under what license is the code on this blog licensed? I know there is some sort of license on the code in the Code Snippet Repository, but I cannot find this implementation of the routine there.

    Thanks for the blog post

    ReplyDelete
  2. This is just example code, so feel free to do want with it.

    I have a draft TArray class that I intended to add to the Code Snippets database, but never got round to. If it ever gets released that code, like everything in the database, will be MIT licensed.

    ReplyDelete

Post a Comment

Comments are very welcome, but please don't comment here if:

1) You have a query about, or a bug report for, one of my programs or libraries. Most of my posts contain a link to the relevant repository where there will be an issue tracker you can use.

2) You have a query about any 3rd party programs I feature, please address them to the program's developer(s) - there will be a link in the post.

3) You're one of the tiny, tiny minority who are aggressive or abusive - in the bin you go!

Thanks

Popular posts from this blog

New String Property Editor Planned For RAD Studio 12 Yukon 🤞

Multi-line String Literals Planned For Delphi 12 Yukon🤞

Call JavaScript in a TWebBrowser and get a result back