You can use the HashSet<double> to find out if there is a duplicate:
public List<double> SortDoppelganger(List<double> inputFitnessList, double replacementValue = 0) { HashSet<double> doppelgangerFinder = new HashSet<double>(); for (int i = 0; i < inputFitnessList.Count; i++) { double value = inputFitnessList[i]; bool istDoppelganger = !doppelgangerFinder.Add(value); if (istDoppelganger) inputFitnessList[i] = replacementValue; } return inputFitnessList; }
This solution modifies the original list. If this is not desired, create a copy at the beginning using var newList = new List<double>(inputFitnessList) .
For what it's worth, here is a general extension method that works with any type:
public static List<T> ReplaceDuplicates<T>(this IEnumerable<T> sequence, T replacementValue) { HashSet<T> duplicateFinder = new HashSet<T>(); List<T> returnList = new List<T>(); foreach (T item in sequence) { bool isDuplicate = !duplicateFinder.Add(item); returnList.Add(isDuplicate ? replacementValue : item); } return returnList; }
Explanation : user3185569 is right, I forgot to mention what you did wrong. The main problem is that you are trying to assign the replacement value to the next local variable:
double next = newFitnessList[j]; if(actual == next) { next = Nothing; }
In this case, this has nothing to do with differences in values ββor reference types. The only reason this does not work is because you only change the value of the variable. Not the value that the variable previously indicated ( newFitnessList[j] ). The variable does not even know that it was associated with the list. He just knows the value of storage. If it were a reference type, the problem would be the same. Replacing it with a different value will not change the list at all.
To shorten the long story, this will fix the underlying problem:
double next = newFitnessList[j]; if(actual == next) { newFitnessList[j] = Nothing; }
source share