我正在尝试将使用Java Comparator
接口的lambda表达式转换为C#。我收到以下错误:
无法将lambda表达式转换为type “
System.Collections.IComparer
”因为它不是委托类型。
我尝试切换到Comparison<T>
,但它不适用于我的Array.Sort
方法:
Array.Sort(Population, Population[0].Comparator);
Array.Sort(population, 0, population.Length, population[0].Comparator);
PregancyIndividual实现IGeneticIndividual接口。
public virtual IGeneticIndividual[] selectPopulation(IGeneticIndividual[] population)
{
IGeneticIndividual[] res = new IGeneticIndividual[population.Length];
Array.Sort(population, 0, population.Length, population[0].Comparator);
这是我的Java代码:
@Override
public Comparator getComparator() {
Comparator<PregnancyIndividual> IndividualFitnessComparator
= (PregnancyIndividual ind1, PregnancyIndividual ind2) -> {
int res = 1;
double fitness1 = ind1.getFitnessCalculator().calculateFitness(ind1);
double fitness2 = ind2.getFitnessCalculator().calculateFitness(ind2);
if (fitness1 > fitness2) {
return -1;
}
if (fitness1 == fitness2) {
return 0;
}
return res;
};
return IndividualFitnessComparator;
}
PregnancyIndividual
实现我自己的界面:
public class PregnancyIndividual implements IGeneticIndividual
我现在正在尝试为C#实现我的代码:
public virtual IComparer Comparator
{
get
{
//<PregnancyIndividual>
IComparer IndividualFitnessComparator = (PregnancyIndividual ind1, PregnancyIndividual ind2) =>
{
int res = 1;
double fitness1 = ind1.FitnessCalculator.calculateFitness(ind1);
double fitness2 = ind2.FitnessCalculator.calculateFitness(ind2);
if (fitness1 > fitness2)
{
return -1;
}
if (fitness1 == fitness2)
{
return 0;
}
return res;
};
return IndividualFitnessComparator;
}
}
答案 0 :(得分:0)
更改您的PregnancyIndividual类以实现Icomparer并实现比较如下:
class PregnancyIndividual : IComparer
{
int IComparer.Compare(object a, object b)
{
PregnancyIndividual ind1 = (PregnancyIndividual)a;
PregnancyIndividual ind2 = (PregnancyIndividual)b;
int res = 1;
double fitness1 = ind1.FitnessCalculator.calculateFitness(ind1);
double fitness2 = ind2.FitnessCalculator.calculateFitness(ind2);
if (fitness1 > fitness2)
{
return -1;
}
if (fitness1 == fitness2)
{
return 0;
}
return res;
}
}