- Home /
Sort arrays using OrderBy and ThenBy Linq
Im at about my wits end here...Here's the scoop.
I have 4 int arrays we'll call them a, b, c, d for ease sake. Here's what they look like...
a b c d
3 2 20 25
5 3 30 20
5 3 32 21
6 4 40 15
What I need to do is sort them based on the methodology of OrderBy and ThenBy in Linq....So for instance I need to sort the A array highest to lowest (A takes precedence), but, then if values in the A array are the same I need to then sort those same values by the B array to find which A value is really highest and then if the B values are the same move on to C so on and so forth.
So in this scenario the correct sorting should be....
a b c d
6 4 40 15
5 3 32 21
5 3 30 20
3 2 20 25
Here's some sample code because I have to make a class, then set the class values because I can only make a list from a class and then make a OrderBy from a list (so I think)
public class daClass
{
public int[] wfilter, dwfilter, pffilter, pafilter;
}
daClass daValues = new daClass();
daValues.wfilter = wstrip;
daValues.dwfilter = dwstrip;
daValues.pffilter = pfstrip;
daValues.pafilter = pastrip;
var arrays = new List<daClass>();
var orderedList = arrays.OrderBy(p => p.wfilter).ThenBy(p => p.dwfilter).ThenBy(p => p.pffilter)
.ThenBy(p => p.pafilter).ToArray();
As much as I feel I've made progress I kind of feel like I'm all over the place here. This seems easy but I'm just brain freezing on it. I don't know if I should be doing this by class or if my instance of the class is even filling in values to the class or if the list is even grabbing said values or the sorting is even sorting it correctly...I can't find any way to debug.log the class or the list or the orderedlist. Some suggestions on how to do this would be MUCH appreciated....Thanks guys!
Answer by Summit_Peak · Apr 15, 2018 at 06:03 PM
Try ordering by items in the array rather than ordering the arrays:
var orderedList = daValues.OrderBy(x => x[0]).ThenBy(y => y[1]).ThenBy(z => z[2]).ThenBy(w => w[3]).ToList();
Your answer
Follow this Question
Related Questions
MergeSort function acting strange 0 Answers
adding classes to arrays 2 Answers
How to sort get components? 3 Answers
Scoring System ArgumentOutOfRangeException Error 2 Answers
Car Positioning System 0 Answers