user3571412
user3571412

Reputation: 215

Compare and complete two arrays

I need to compare an array with a array model and complete the structure, like this example:

array = [0,1,2,3,4]
model = [0,0,0,0,0,0,0]

result = [0,1,2,3,4,0,0]

The model can't be changed, it's a reference array.

Any ideas about the best way to achieve this?

Upvotes: 0

Views: 95

Answers (4)

René Vogt
René Vogt

Reputation: 43946

You can do that like that:

var array = new[]{0,1,2,3,4};
var model = new[]{0,0,0,0,0,0,0};

var result = array.Concat(model.Skip(array.Length)).ToArray();

This will concat the missing elements from model at the end of array.


Concat, Skip and ToArray are LINQ extension methods declared in the Enumerable class in namespace System.Linq. So you need to add using System.Linq; to your code.

Upvotes: 4

Mong Zhu
Mong Zhu

Reputation: 23732

Copy the short one into the long one:

int[] array = { 0, 1, 2, 3, 4 };
int[] model = { 0, 0, 0, 0, 0, 0, 0, };


int[] result = model;

array.CopyTo(result, 0);

Console.WriteLine(String.Join(" ", result));

If best means fastest as you wrote in your comment then here is a comparison:

Stopwatch st = new Stopwatch();

int[] array = new int[10000];
int[] model = new int[10200];

st.Start();
var asdf = array.Concat(model.Skip(array.Length)).ToArray();
st.Stop();
Console.WriteLine("Concat: " + st.ElapsedMilliseconds);


int[] arraya = new int[10000];
int[]  modela = new int[10200];

st.Restart();
int[] result = modela;
arraya.CopyTo(result, 0);
st.Stop();
Console.WriteLine("Copy: " + st.ElapsedMilliseconds);

Upvotes: 3

Matthew Whited
Matthew Whited

Reputation: 22443

If you know the array lengths upfront you can do this...

int[] array = { 0, 1, 2, 3, 4 };
int[] model = { 0, 0, 0, 0, 0, 0, 0, };

Array.Copy(array, model, array.Length);

if not you can so something like this...

int[] model = { 0, 1, 2, 3, 4 };
var array = new int[7];

var shorter = array.Length < model.Length ? array : model;
var longer = array.Length >= model.Length ? array : model;
Array.Copy(shorter, longer, shorter.Length);

... fastest without mutation of originals ...

int[] array = { 0, 1, 2, 3, 4 };
int[] model = { 4,5,6,7,8,9,1, };

var x = array.Length < model.Length ?
    new { s = array, l = model, sl = array.Length, ll = model.Length } :
    new { s = model, l = array, sl = model.Length, ll = array.Length };

var result = new int[x.ll];

Array.Copy(x.s, result, x.sl);
Array.Copy(x.l, x.sl, result, x.sl, x.ll - x.sl);

Upvotes: 2

Chibueze Opata
Chibueze Opata

Reputation: 10044

Here's my version... Might be a bit faster than LINQ. My assumption is you're replacing based on array with larger number but I may be wrong.

var array = new[]{0,1,2,3,4};
var model = new[]{0,0,0,0,0,0,0};
for(int i = 0; i < array.Length; i++)
{    
    if(array[i] > model[i])
    {
        model[i] = array[i];
    }
}

If not you can simply do an Array.Copy

Upvotes: -1

Related Questions