2

I have an array of unique values specified in some arbitrary order; I have another array of (nearly) the same values as the first array, but some values may be missing, and they are ordered in a completely different way.
How do I order values in the second array in the same order as the first one?

UPD for example:

array 1: 4, 8, 2, 5, 9, 3
array 2: 5, 8, 4, 2
required result: 4, 8, 2, 5

3
  • 3
    show example data of both arrays and what result array you want for the second one. Commented Nov 30, 2016 at 4:06
  • what's the max size of the second array? Commented Nov 30, 2016 at 4:16
  • @jdigital, it can be big. Commented Nov 30, 2016 at 4:21

3 Answers 3

3

You could check that each element in array 1 exists in array 2 and take them in that order:

  var result = array1.Where(a => array2.Contains(a));
Sign up to request clarification or add additional context in comments.

Comments

3
int[] array1 = new int[] { 4, 8, 2, 5, 9, 3 };
int[] array2 = new int[] { 5, 8, 4, 2 };


array2 = array1.Intersect(array2).ToArray();

1 Comment

@user626528 this answer is much more efficient for big arrays because it uses Set internally for the seccond array
0

Ok,lets consider logic than code.

If we consider the case where second array is subset of the first array We can do One thing. let's create an array of type Boolean of size first array. Consider each element of second array and traverse through first array. If you find a match then make corresponding Boolean index as TRUE. Finally you will get a Boolean array of TRUE and FALSE combination. then you can print all indexes of first array with Boolean value TRUE.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.