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

user626528
  • 13,999
  • 30
  • 78
  • 146

3 Answers3

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


array2 = array1.Intersect(array2).ToArray();
mybirthname
  • 17,949
  • 3
  • 31
  • 55
  • 1
    @user626528 this answer is much more efficient for big arrays because it uses [Set internally](https://referencesource.microsoft.com/#System.Core/System/Linq/Enumerable.cs,ae06318d1f5fb355) for the seccond array – Slai Nov 30 '16 at 04:47
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));
Ian Mercer
  • 38,490
  • 8
  • 97
  • 133
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.

Anuroop Pendela
  • 147
  • 1
  • 8