C# 中对象数组的排序(相当于 std::sort)

2024-01-04

如何在 C# 中对字符串数组进行升序排序,我想在 C++ 中使用类似 std::sort 的东西:

 std::sort(population.begin(), population.end())

我需要对对象列表进行排序。列表中的对象是 Genome 类的实例。我重载了运算符<和操作员>在那堂课上。

 class Genome
{
    public List<double> weights;
    public double fitness;

    public Genome()
    {
        fitness = 0.0;
        weights = new List<double>();
    }

    public Genome(List<double> weights, double fitness) {
        this.weights = weights;
        this.fitness = fitness;
    }

    
    public static bool operator <(Genome lhs, Genome rhs)
    {
        return (lhs.fitness < rhs.fitness);
    }

    public static bool operator >(Genome lhs, Genome rhs) {
        return (lhs.fitness > rhs.fitness);
    }

}

人口的申报方式如下:

List<Genome> population = new List<Genome>();

我怎样才能对这个数组进行排序?运算符重载运算符可以像 C++ 中那样使用


population.OrderBy(x => x.weights); 

or:

population.OrderByDescending(x => x.fitness); 
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

C# 中对象数组的排序(相当于 std::sort) 的相关文章

随机推荐