c# Lambda表达式与IComparer和Array.排序(从Java转换到c#)

本文关键字:Java 转换 Array 表达式 Lambda IComparer 排序 | 更新日期: 2023-09-27 18:07:20

我正试图将使用Comparator接口的lambda表达式从Java转换为c#。我得到了以下错误:

不能将lambda表达式转换为类型' System.Collections.IComparer ',因为它不是委托类型。

我试图切换到Comparison<T>,但它不与我的Array.Sort方法工作:

Array.Sort(Population, Population[0].Comparator);
Array.Sort(population, 0, population.Length, population[0].Comparator);

preancyindividual实现了igenticindividual接口

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;
        }
    }

c# Lambda表达式与IComparer和Array.排序(从Java转换到c#)

改变你的pregnyindividual类来实现Icomparer和实现Compare如下:

    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;
        }    
    }