How to efficiently get highest & lowest values from a List<double?>, and then modify them?
- by DaveDev
I have to get the sum of a list of doubles. If the sum is 100, I have to decrement from the highest number until it's = 100. If the sum is < 100, I have to increment the lowest number until it's = 100. I can do this by looping though the list, assigning the values to placeholder variables and testing which is higher or lower but I'm wondering if any gurus out there could suggest a super cool & efficient way to do this? The code below basically outlines what I'm trying to achieve:
var splitValues = new List<double?>();
splitValues.Add(Math.Round(assetSplit.EquityTypeSplit() ?? 0));
splitValues.Add(Math.Round(assetSplit.PropertyTypeSplit() ?? 0));
splitValues.Add(Math.Round(assetSplit.FixedInterestTypeSplit() ?? 0));
splitValues.Add(Math.Round(assetSplit.CashTypeSplit() ?? 0));
var listSum = splitValues.Sum(split => split.Value);
if (listSum != 100)
{
if (listSum > 100)
{
// how to get highest value and decrement by 1 until listSum == 100
// then reassign back into the splitValues list?
var highest = // ??
}
else
{
// how to get lowest where value is > 0, and increment by 1 until listSum == 100
// then reassign back into the splitValues list?
var lowest = // ??
}
}
update: the list has to remain in the same order as the items are added.