3

This is an oddly specific case, but I have 3 arrays, all with flexible sizes(but same) and valuables and I need to order one of them using the other 2. For instance

int[] array1 = new int[0 ,1 ,1 ,1 ,0];
int[] array2 = new int[5 ,3 ,4 ,2 ,0];
int[] array3 = new int[0 ,1 ,2 ,3 ,4];

// Results array3 == [2,1,3,0,4]

I want to order the third array first by the values of the first one and using the second one in cases the first array couldn't order. Is there a way to do it cleanly or do I have to hardcode it?

johnny 5
  • 19,893
  • 50
  • 121
  • 195
Joska
  • 39
  • 1

2 Answers2

1

As the guys said in the comments, doing it in tuples or a class would be better so

        var array1 = new int[] { 0, 1, 1, 1, 0};
        var array2 = new int[] { 5, 3, 4, 2, 0};
        var array3 = new int[] { 0, 1, 2, 3, 4};

        var listOfTuples = array1.Select((t, i) => new Tuple<int, int, int>(t, array2[i], array3[i])).ToList();
        listOfTuples = listOfTuples.OrderBy(t => new {t.Item1, t.Item2}).ToList();

These would be ordered by array1 then array2.

If you want a solution without tulples please add in the comments.

Moaead Yahya
  • 211
  • 1
  • 5
  • Since unity uses a very old version of c#, I don't have access to tulples :/ – Joska May 05 '18 at 20:24
  • Easy to create one though https://stackoverflow.com/questions/7120845/equivalent-of-tuple-net-4-for-net-framework-3-5 – Moaead Yahya May 05 '18 at 20:33
  • Surely you can just change the `.OrderBy(...)` for `.OrderBy(t => t.Item1).ThenBy(t => t.Item2)` to do it without creating an extra IComparer. – Trevor May 05 '18 at 21:13
  • @Trevor I kinda was not aware of ThenBy. I edited my answer. Basically now it's really a one-liner, even without native c# tuples. – adjan May 05 '18 at 22:03
1

To have it work with older .NET versions like 3.5, transform the arrays using Select() into a list of anonymous objects (which are basically like tuples). Then use OrderBy() and ThenBy() to order the list according to the values from the first array and the second array:

var array1 = new int[] { 0, 1, 1, 1, 0};
var array2 = new int[] { 5, 3, 4, 2, 0};
var array3 = new int[] { 0, 1, 2, 3, 4};

var list = array1.Select((t, i) => new { X1 = t, X2 = array2[i], X3 = array3[i] })
                 .OrderBy(t => t.X1) // first order by values from array1
                 .ThenBy(t => t.X2)  // then by values from array2
                 .Select(t => t.X3)  // we only want values from array3
                 .Reverse();         // put into right order

Output:

2 1 3 0 4

adjan
  • 13,371
  • 2
  • 31
  • 48