Home > other >  complex sorting in c# equivalent to pythons itemgetter,
complex sorting in c# equivalent to pythons itemgetter,

Time:01-22

  1. I have a List<bool[]> ls, where each inners index is either true or false.
  2. I have a List<Tuple<int,int>> importance, where each Item1 is a indexPosition and Item2 the magnitude of importance of that index.
  3. Each bool[] is of same length.
  4. Also the list is preSorted, so each bool[] has the same count of true and false indices, just in different positions.

I need to sort the outer collection in a way, that the inner arrays that are true at the most important index come first. If there are multiple arrays, that have the mostImportant index == true, then they need to be sorted by the second most important index. Etc.

Example:

//Item1: importantIndex; Item2: magnitudeOfImportance
var importance = new List<Tuple<int,int>> {Tuple.Create(3,3), Tuple.Create(5,2), Tuple.Create(1,1)};
var ls = new List<bool[6]>{
  new bool[6]{false, false, true, false, false, true},
  new bool[6]{false, true, false, false, false, true},
  new bool[6]{false, false, false, true, true, false},
  new bool[6]{false, true, false, true, false, false},
  new bool[6]{false, false, false, true, false, true}}

After Sorting with two important indices :

importance:= [(3,3)(5,2)(1,1)]


          0 1 2 3 4 5
ls[0] = [ - - -   -   ]
ls[1] = [ -   -   - - ]
ls[2] = [ - - -     - ]
ls[3] = [ -   - - -   ]
ls[4] = [ - -   - -   ]

CodePudding user response:

I see in the sample data that importance is already sorted so the most important items come in order. I will continue assuming this is true. If not, sorting that set adds one line of code (importance = importance.OrderByDescending(i => i.Item2).ToList();)

That out of the way, this should do the job:

//seed result with a valid IOrderedEnumerable for first level
var result = ls.OrderBy(ba => ba[importance[0].Item1]?0:1);
// check remaining items
for (int i = 1; i<importance.Count; i  )
{
   int y = i; //prevent closure over i
   result = result.ThenBy(ba => ba[importance[y].Item1]?0:1);
}
ls = result.ToList();

See it work here:

https://dotnetfiddle.net/qntayC

  •  Tags:  
  • Related