'Sort a list of Expressions in Optano C#

Edit: To reword my opening explanation to hopefully make it clearer: "How can I write an expression that represents the mean of the lowest N expressions in an unordered list?" The list includes negative values.

TLDR: how do I make a list of Expressions that is sorted by the values to which each Expression would evaluate?

Full question: I'm using Optano with the Gurobi solver in C# (using VS2019) to minimise the sum of the lowest 5% of a set of weighted values (the weights being the variables added to the model).

To the find the lowest 5% I need to sort the values calculated by the model. One way or another, I need to be able to compare two values, but I can't work out how. If I have List the Sort() method doesn't work for obvious reasons.

Instead, because it's more efficient and is much simpler code than a sorting algorithm (which I have also tried to no avail, using selection sorting), I have a little foreach that finds the correct position in a list into which to insert the new value so that I end up with a sorted list.

Expression[] expressionPairForMin = new Expression[2];
expressionPairForMin[0] = weightedValueTemp; //The new Expression I want to insert into the sorted list.
foreach (Expression weightedValue in allWeightedValues)
{
    expressionPairForMin[1] = weightedValue;
    //if (weightedValueTemp < weightedValue) { break; } //What I want to do, which doesn't work of course.
    if (Expression.Equals(Expression.Minimum(expressionPairForMin), weightedValueTemp)) { break; } //One of several ideas I've tried.
    insertPosition++;
}
portfolioWeightedReturns.Insert(insertPosition, weightedValueTemp);

The if I have there is trying to say: if the minimum of the two Expressions is the same as the first Expression, then the first Expression must be the smaller of the two.

Later, I take the sum (using Expression.Sum) of the first n values (which is what's returned as an Expression for the Objective).

My code works if I use Expression.Evaluate on the objective with hardcoded weights as input variables and use the double values more directly, but not when I run the solver. It just doesn't sort the list in that case, as the if never returns true and so weightedValueTemp is always inserted at the end of the list.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source