我如何样一类的ArrayList? [英] How can i sort Arraylist with a class?

查看:152
本文介绍了我如何样一类的ArrayList?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何索思下面的ArrayList根据int值。但是,如果你低于codeS错误编译:无效操作异常...详情:无法比较数组中的两个元素

 命名空间SortArray
{
    类节目
    {
        静态无效的主要(字串[] args)
        {
            ArrayList的otomobil =新的ArrayList();
            otomobil.Add(新Otomobil(){型号= 2000,马尔卡=奔驰,伦克=Kırmızı});
            otomobil.Add(新Otomobil(){型号= 2002,马尔卡=欧宝,伦克=耶希尔});
            otomobil.Add(新Otomobil(){型号= 2009,马尔卡=奥迪,伦克=马维});

            otomobil.Sort();
            的for(int i = 0;我 outer.Model)
                返回1;
            否则,如果(this.Model  

解决方案

类Otomobil:IComparable的

How can i soth below arraylist according to int value. But if you compiled below codes error : Invalid Operation Exception... Detail : Failed to compare two elements in the array.

namespace SortArray
{
    class Program
    {
        static void Main(string[] args)
        {
            ArrayList otomobil = new ArrayList();
            otomobil.Add(new Otomobil() { Model = 2000, Marka = "mercedes", Renk = "Kırmızı" });
            otomobil.Add(new Otomobil() { Model = 2002, Marka = "Opel", Renk = "Yeşil" });
            otomobil.Add(new Otomobil() { Model = 2009, Marka = "Audi", Renk = "Mavi" });

            otomobil.Sort();
            for (int i = 0; i < otomobil.Count; i++)
            {
                Console.WriteLine(otomobil[i].ToString());
            }

        }
    }

    public class Otomobil
    {
        public string Marka { get; set; }
        public int Model { get; set; }
        public string Renk { get; set; }

        public Otomobil()
        {

        }

        public override string ToString()
        {
            return Marka + "(" + Model.ToString() + "-" + Renk + ")";
        }

        public int CompareTo(object obj)
        {
            if (obj == null)
                return 1;


            Otomobil outer = obj as Otomobil;
            if (outer == null)
                throw new ArgumentException();

            if (this.Model > outer.Model)
                return 1;
            else if (this.Model < outer.Model)
                return -1;
            else return 0;
        } 
    }
}

解决方案

class Otomobil : IComparable

这篇关于我如何样一类的ArrayList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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