问题
检查集合多次包含相同的数字.
If it does contain the same numbers more than once,then I want to
keep the first number and give a new value to the rest of the numbers,
which are the same as the first one.
list newFitnessList确实包含这些数字:
0. 4054.230995 --> after code= 4054.230995 1. 4041.416004 --> after code= 4041.416004 2. 3926.227397 --> after code= 3926.227397 3. 4722.250903 --> after code= 4722.250903 4. 4722.250903 --> after code= 0 5. 4226.636776 --> after code= 4226.636776 6. 4061.499026 --> after code= 4061.499026 7. 3876.278254 --> after code= 3876.278254 8. 4041.416004 --> after code= 0 9. 4779.468077 --> after code= 4779.468077 10. 4226.636776 --> after code= 0 11. 3876.278254 --> after code= 0 12. 4779.468077 --> after code= 0 13. 3926.227397 --> after code= 0
为了实现上面解释的解决方案,我尝试了以下代码,但没有发生任何事情.列表的输出与以前相同:
public List<double> sortDoppelganger(List<double> inputFitnessList) { List<double> newFitnessList = inputFitnessList.ToList(); for(int i = 0; i < newFitnessList.Count; i++) { double Nothing=0; double actual = newFitnessList[i]; for(int j = newFitnessList.Count-1; j >= 0; j--) { double next = newFitnessList[j]; if(actual == next) { next = Nothing; } } } return newFitnessList; }
如果有人知道我的代码有什么问题,我将非常感激.
也许最好不要隐藏,我是编程的新手.
看完解释后:
我尝试了两个想法的解释.第一个是@Tim Schmelter的想法,第二个想法来自@ user3185569.
解决方法
你可以使用HashSet< double>找出是否有重复:
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; }
此解决方案修改原始列表.如果不需要,可以使用var newList = new List< double>(inputFitnessList)在开头创建一个副本.
对于它的价值,这里是一个适用于任何类型的通用扩展方法:
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; }
说明:user3185569是对的,我忘了提到你做错了什么.主要问题是您尝试将替换值分配给下一个局部变量:
double next = newFitnessList[j]; if(actual == next) { next = Nothing; }
在这种情况下,它与值或引用类型的差异无关.这不起作用的唯一原因是您只修改变量的值.不是变量之前引用的值(newFitnessList [j]).该变量甚至不知道它已链接到列表.它只知道存储的价值.如果它是参考类型,问题将是相同的.通过将其替换为另一个值,列表将不会被修改.
简而言之,这将解决主要问题:
double next = newFitnessList[j]; if(actual == next) { newFitnessList[j] = Nothing; }