C#记录(三):List泛型

具体参考实例:https://mp.csdn.net/console/editor/html/105405707

一、泛型实例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Person p1 = new Person("xiaoming", 20);
            Person p2 = new Person("xiaohong", 22);
            Person p3 = new Person("xiaowang", 21);

            List<Person> persons = new List<Person>();
            persons.Add(p1);
            persons.Add(p2);
            persons.Add(p3);
            Console.Write(persons[1].Name);
        }
    }
}

namespace ConsoleApplication1
{
    class Person
    {
        private string _Name;
        private int _Age;

        //创建对象
        public Person(string Name, int Age)
        {
            this._Name = Name;
            this._Age = Age;
        }
        //姓名
        public string Name
        {
            get { return _Name; }
        }
        //年龄
        public int Age
        {
            get { return _Age;}
        }
    }
}

二、自定义对象类型默认排序

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Person p1 = new Person("xiaoming", 20);
            Person p2 = new Person("xiaohong", 22);
            Person p3 = new Person("xiaowang", 21);

            List<Person> persons = new List<Person>();
            persons.Add(p1);
            persons.Add(p2);
            persons.Add(p3);

            persons.Sort();

            foreach(Person p in persons)
            {
                Console.WriteLine("{0}, {1}",p.Name, p.Age);  //WriteLine自动换行打印
            }
        }
    }
}

namespace ConsoleApplication1
{
    class Person : IComparable<Person>
    {
        private string _Name;
        private int _Age;

        //创建对象
        public Person(string Name, int Age)
        {
            this._Name = Name;
            this._Age = Age;
        }
        //姓名
        public string Name
        {
            get { return _Name; }
        }
        //年龄
        public int Age
        {
            get { return _Age;}
        }

        //对象本身不是一个具体的值,在排序逻辑上显然要选择对象的一个属性进行排序。
        public int CompareTo(Person other)
        {
            //return this.Age.CompareTo(other.Age);     //升序
            return other.Age.CompareTo(this.Age);       //降序
        }
    }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值