0

I'm using this code to sort an Array

Array.Sort(numsFoundedCount, numsFoundedSorted);

Which it works but when 2 items of numsFoundedSorted have the same numsFoundedCount value i want them (the numsFoundedSorted items) to be sorted from min to max.

int[] numsFoundedCount = new int[80];
int[] numsFoundedSorted = new int[80];

numsFoundedSorted inludes an integer and numsFoundedCount represent how many times this integer has appear. so i want to sort numsFoundedSorted from minumum to maximum according to numsFoundedCount.

I want both of the arrays to be sorted like in Array.Sort For example:

numsFoundedSorted {5,7,6,8}
numsFoundedCount {3,2,2,1}

After sort must be:

numsFoundedSorted {8,6,7,5}
numsFoundedCount {1,2,2,3}
2
  • 3
    can you give us more details about the definitions of numsFoundedCount and numsFoundedSorted? Commented Feb 27, 2018 at 16:21
  • its a simple int[] array Commented Feb 27, 2018 at 18:03

1 Answer 1

2

If i understood right, this is what you want

var numsFoundedSorted = numsFoundedSorted
    .Select((item, idx) => new { Index = idx, Value = item })
    .OrderBy(tuple => numsFoundedCount[tuple.Index])
    .ThenBy(tuple => tuple.Value)
    .Select(tuple => tuple.Value)
    .ToArray();

Array.Sort(numsFoundedCount);

There is no options to do it with Array.Sort

And if you are already using C# 7 features you can replace new { Index = idx, Value = item } with (Index: idx, Value: item)

Sign up to request clarification or add additional context in comments.

2 Comments

I guess this will only sort numsFoundedSorted array. to also sort numsFoundedCount all i have to do after your code is Array.Sort(numsFoundedCount); Also will your code sort numsFoundedSorted items from min to max? cause i see on OrderBy you have set numsFoundedCount
ThenBy(tuple => tuple.Value) this line here makes the sorting of numsFoundedSorted by value from min to max in case of equivalent value of numsFoundedCount in same position. And yes, this code just sorts numsFoundedSorted

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.