在C#中对对象数组进行排序(等效于std :: sort) [英] Sort array of object in C# (equivalent of std::sort)

查看:585
本文介绍了在C#中对对象数组进行排序(等效于std :: sort)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I sort array of strings ascending in c#, I want use something like std::sort in C++:

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

我需要对对象列表进行排序.列表中的对象是Genome类的实例.我在该课程中重载了运算符< 和运算符> .

I need to sort list of obects. The objects in list are instances of Genome class. I overloaded operator < and operator > in that class.

 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 ++中一样?

How can I sort this array?? Can be usede the operator overloaded operator < like in C++?

推荐答案

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

或:

population.OrderByDescending(x => x.fitness); 

这篇关于在C#中对对象数组进行排序(等效于std :: sort)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆